django:根据列匹配的数量对行进行排序(django: sort rows based on number of column matching)

编程入门 行业动态 更新时间:2024-10-26 10:30:32
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')

更多推荐

本文发布于:2023-08-07 22:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466389.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数量   rows   sort   django   column

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!