django:根据列匹配数对行进行排序
django: sort rows based on number of column matching
我有一个模型:-
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 个字段,因此 on.Can 有人建议一种有效执行此操作的方法吗?
您可以使用 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')
我有一个模型:-
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 个字段,因此 on.Can 有人建议一种有效执行此操作的方法吗?
您可以使用 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')