HNMN3
HNMN3

Reputation: 542

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.

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. I can do that at the python level by fetching all the Posts and then checking their tags.

is there any way we can directly fetch it from the DB? Using the DJango QuerySet.

Any help would be appreciated!!

Thanks in Advance!!

Upvotes: 0

Views: 60

Answers (3)

Houda
Houda

Reputation: 691

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)))

Upvotes: 1

Stevy
Stevy

Reputation: 3387

Using a Q object you can query for Post objects which both have "python" AND "django" like this:

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

Upvotes: 1

Arvind Kumar
Arvind Kumar

Reputation: 973

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

Upvotes: 1

Related Questions