By "retrieving the matching tags" you mean fetching `Tag` objects?
Well I guess what you can do is to use `prefetch_related <https://docs.djangoproject.com/en/1.9/ref/models/querysets/#prefetch-related>` with custom `Prefetch <https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.Prefetch>` object. blogs = Blog.objects.prefetch_related( models.Prefetch('tags', queryset=Tag.objects.filter(name__in=['python', 'java']) to_attr='my_tags' ) ) #usage for blog in blogs: print blog.my_tags On Tuesday, July 12, 2016 at 2:28:30 PM UTC+3, Ramashish Baranwal wrote: > > Hi, > > I have the following model definitions: > > class Tag(models.Model): > name = models.CharField(max_length=16) > > class Blog(models.Model): > name = models.CharField(max_length=16) > tags = models.ManyToManyField(Tag, blank=True) > > > > I want to select blogs with more than one tags. Here is what I am doing > (for two tags)- > > # select blogs for python and java > blogs = Blog.objects.filter(tags__name='python').filter(tags__name='java') > > > > This INNER joins Tag with Blog twice, each time filtering on the given > name. This works well. Now I want to retrieve the matching tags. If it were > a single join, I would have done- > > blogs = blogs.annotate(tag=F('tags__name')) > > Doing this still works, but only retrieves the last tag. How do I retrieve > the tag name for each join, giving them different names? Something like- > > # Below should give tag1 = 'python', tag2 = 'java' > blogs = blogs.annotate(tag1=?, tag2=?) > > Thanks, > Ramashish > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e148c289-6f10-4f6d-a892-8b31f85a3887%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.

