django:根据列匹配数对行进行排序

django:根据列匹配数对行进行排序,django,django-orm,Django,Django Orm,我有一个模型:- 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) occupatio

我有一个模型:-

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)     ....

对于一个用户配置文件(比如:('masters'、'India'、'student'),我想根据它与给定用户配置文件匹配的字段数量过滤所有用户配置文件,即首先是所有3个匹配配置文件的字段,然后是任何2个匹配配置文件的字段,依此类推。有人能建议一种有效的方法吗?

您可以使用


在.order_by('matched')之前缺少一个“)”。另外,它在前面显示了错误,但当我将字段“occulation\u matched”重命名为其他名称时,它工作了(“。如果有效,您能接受答案吗?它有时向我显示错误,有时有效。FieldError:无法将关键字“education_matched”解析为field。已修复。我将annotate拆分为2个annotate。是的,有效。在早期查询中出现错误的原因是什么?是因为执行顺序吗?
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')