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) ....对于一个用户配置文件(让我们说:('主人','印度','学生')我想过滤所有用户配置文件,它按照与给定用户配置文件匹配的字段数排序,即首先匹配配置文件的所有3个字段然后任何2个匹配配置文件的字段等等。任何人都建议有效地执行此操作的方法吗?
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?
最满意答案
您可以使用条件表达式实现此目的。
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')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')更多推荐
发布评论