简体   繁体   English

如何在多对多字段中查询具有所有给定对象的对象?

[英]How to query the objects having all the given objects in Many To Many Field?

I was trying to find out one way where I can query all the objects of one table which are having the given objects as ManyToMany Field.我试图找出一种方法,我可以查询一个表的所有对象,这些对象将给定对象作为 ManyToMany 字段。

Please take below example:请看下面的例子:

class Post(models.Model):
    title = models.CharField(max_length=50)
    text = models.CharField(max_length=1000)
    pub_date = models.DateTimeField('date published')
    author = models.CharField(max_length=30)
    mail = models.EmailField()

class Tag(models.Model):
    name = models.CharField(max_length=15)
    posts = models.ManyToManyField(Post, related_name="tags")

Here I want to fetch all the posts having both "python" and "django" in the tag list.在这里,我想获取标签列表中同时包含“python”和“django”的所有帖子。 I can do that at the python level by fetching all the Posts and then checking their tags.我可以在 python 级别通过获取所有帖子然后检查它们的标签来做到这一点。

is there any way we can directly fetch it from the DB?有什么方法可以直接从数据库中获取它? Using the DJango QuerySet.使用 DJango 查询集。

Any help would be appreciated!!任何帮助,将不胜感激!!

Thanks in Advance!!提前致谢!!

Yes, you can try the following -是的,您可以尝试以下方法 -

from django.db.models import Q

filteredPosts = Post.objects.filter(Q(tags__name='python')|Q(tags__name='django'))

Hope it helps希望能帮助到你

Try this:尝试这个:

Post.objects.filter(id__in=list(Tag.objects.filter(name__in=['Python', 'Django']).values_list('posts', flat=True)))

UPDATE:更新:

Q1 = Tag.objects.filter(name__exact='Django').values_list('posts', flat=True)
Q2 = Tag.objects.filter(name__exact='Python').values_list('posts', flat=True)
Post.objects.filter(id__in=list(set(Q2) & set(Q1)))

Using a Q object you can query for Post objects which both have "python" AND "django" like this:使用 Q object 您可以查询具有“python”“django”的Post对象,如下所示:

from django.db.models import Q

qs = Post.objects.filter(Q(tags__name='python') & Q(tags__name='django'))

More information about how to make complex queries using the Q object in the docs有关如何使用文档中的 Q object 进行复杂查询的更多信息

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

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