ManytoMany过滤精确列表

ManytoMany过滤精确列表

本文介绍了Django ManytoMany过滤精确列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个id的列表:c = ['1','2','3']

Suppose I have a list of id's: c = ['1', '2' , '3']

class Topic(Model):

 categories=ManyToManyField(Category)

我可以过滤具有来自c的id的唯一类别的主题吗?

How can I filter topics that have exact and only categories with id's from c?

推荐答案

您需要调用 c 列表中的每个元素的.filter(categories = category_id)

You need to call .filter(categories=category_id) for each element in the c list.

c = [1, 2, 3]
topics = reduce(lambda qs, pk: qs.filter(categories=pk), c, Topic.objects.all())

然后,如果要排除其他类别的主题(例如, [1,2,3,4] ),那么您需要 .annotate .filter 总数。

And then if you want to exclude topics with additional categories (e.g. a topic with [1,2,3,4]), then you need to .annotate and .filter on the total count.

c = [1, 2, 3]
initial_qs = Topic.objects.annotate(cnt=models.Count('categories')).filter(cnt=len(c))
topics = reduce(lambda qs, pk: qs.filter(categories=pk), c, initial_qs)

这篇关于Django ManytoMany过滤精确列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:12