简体   繁体   English

Django通过属性与另一个QuerySet的交集计数对模型对象进行排序

[英]Django sort model objects by intersection count of a property with another QuerySet

I have a problem with Django querying. 我有Django查询的问题。 I searched through web but still couldn't find a solution to it. 我通过网络搜索但仍无法找到解决方案。

I have a model called Question: 我有一个叫做问题的模型:

class Question(models.Model):
    ...
    tags = models.ManyToManyField(Tag, related_name='tagged_questions')
    ...

And I need to write a method which is as below: 我需要编写一个方法,如下所示:

def get_recommended_questions(request):
    ...
    interested_tags = user.interested_tags.all()
    recommended_questions_list = ... // I need help here

I need to get a list of Question objects, which are sorted by the intersection count of their tags with interested_tags 我需要的清单Question的对象,这是由他们的交集数排序tagsinterested_tags

For example: 例如:

interested_tags = [A, B, C]

And I have following questions in the database: 我在数据库中有以下问题:

q1.tags = [A, B, C] // intersection count = 3
q2.tags = [D] // intersection count = 0
q3.tags = [A, B, D] // intersection count = 2
q4.tags = [A, D] // intersection count = 1

What I want to get is: 我想得到的是:

recommended_questions_list = [q1, q3, q4]

I want to know if there is a way to do this without using raw SQL. 我想知道是否有办法在不使用原始SQL的情况下执行此操作。

Thank you very much for your help! 非常感谢您的帮助!

In this, first we require to get all the questions that has any of the tag in which user is interested. 在此,首先我们要求获得具有用户感兴趣的任何标签的所有questions Then we can sort it based on the total matched tags between user and question. 然后我们可以根据用户和问题之间的匹配tags进行排序。

Sample code: 示例代码:

interested_tags_ids = user.interested_tags.all().values_list('id', flat=True)
questions = Question.objects.filter(tags__in=interested_tags_ids).prefetch_related('tags')
interested_tags_set = set(interested_tags_ids)

sort_func = lambda question: len(set(question.tags.all().values_list('id', flat=True)) & interested_tags_set)
recommended_questions_list = sorted(questions, key=sort_func, reverse=True)

That's long query so I will go step by step 这是一个很长的问题,所以我会一步一步走

def get_recommended_questions(request):
    ...
    interested_tags = user.interested_tags.all()
    questions = Question.objects.all()
    recommended_questions_list = [(question, 
             len(set(interested_tags)&set(list(question.tags.all())))) 
             for question in questions]
    # the above list has tuples with question object and intersection count

Now you can sort however you want 现在您可以根据需要进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM