Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!