I have an article model with m2m relationships to model Tag,
I intend to filter articles which have tags both "python" and "django"
I tried Q along with &
In [184]: from django.db.models import Q
In [185]: articles = Article.objects.filter(Q(tags__name="python") & Q(tags__name=
...: "django"))
In [186]: articles
Out[186]: <QuerySet []>
It return a null Queryset
Alternatively I tested
In [202]: articles = Article.objects.filter(Q(tags__name="python")).filter(Q(tags_
...: _name="django"))
In [203]: articles
Out[203]: <QuerySet [<Article: Test new tags>, <Article: Django Tutorial>]>
I worked and solved the problem.
However, I am very confused with the failing of Q()&Q()
, should I alway utilize filter chain rather than Q() combination to avoid mistakes?