Reputation: 354
Assume there is a list contains all keys to search called taglist
. To filter all Post contains tag in taglist
, I use the following command.
Post.objects.filter(tags__tag__in=taglist).order_by('-id')
and in class Post
tags = models.ManyToManyField('PostMention')
in PostMenthion
class PostMention(models.Model):
tag = models.CharField(unique=True,max_length=200)
and I will get a Query list about the result.
Can I get a list of tuple like(each_result,tag_that_used_to_found_the_result)
?
Upvotes: 1
Views: 397
Reputation: 477220
Yes, we can .annotate(..)
each row with the related Tag
:
from django.db.models import F
Post.objects.filter(
tags__tag__in=taglist
).annotate(
the_tag=F('tags__tag')
).order_by('-id')
Here the Post
objects will have an extra attribute .the_tag
, that contains the string of the tag that matched. In case multiple tags matched, multiple Post
objects will be in the queryset, each with their .the_tag
attribute.
We can post-process this to a 2-tuple, but I think an attribute is a better choice, since then it is clear what this field contains.
Upvotes: 1