Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
django: sort rows based on number of column matching

I have a model:-

class Userprofile(models.Model):
    user=models.OneToOneField(settings.AUTH_USER_MODEL)
    education=models.models.CharField(max_length=20,blank=True,null=True)
    country=models.CharField(max_length=20,blank=True,null=True)
    occupation=models.CharField(max_length=20,blank=True,null=True)     ....

for a user profile (let's say: ('masters','India','student') I want to filter all the user profiles ordered by the number of fields it matches with the given user profile i.e first all 3 fields matching profiles then any 2 fields matching profiles and so on.Can anyone suggest a way to do this efficiently?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can achieve this using conditional expressions.

from django.db.models import Value, Case, When, IntegerField, F

education, country, occupation = 'masters','India','student'
Userprofile.objects.annotate(education_matched=Case(
    When(education=education, then=Value(1)), 
    default=Value(0), 
    output_field=IntegerField()
), country_matched=Case(
    When(country=country, then=Value(1)), 
    default=Value(0), 
    output_field=IntegerField()
), occupation_matched=Case(
    When(occupation=occupation, then=Value(1)), 
    default=Value(0), 
    output_field=IntegerField()
)).
annotate(matched=F('education_matched') + F('country_matched') + F('occupation_matched')).
order_by('matched')
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda