Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - query filter on manytomany is exists

I have such a model:

class News(models.Model):
    # ...
    channels = models.ManyToManyField(Channel)
    # ...

What is the most effective way to fetch news related to channels?

like image 914
Alexander Fedotov Avatar asked Jun 03 '19 21:06

Alexander Fedotov


Video Answer


1 Answers

For a given channel, you can filter with:

News.object.filter(channels=my_channel)

for a collection (list, QuerySet, ...):

News.object.filter(channels__in=my_channel_collection)

For News objects that have at least one (or more) channels, we can query with:

News.objects.filter(channels__isnull=False).distinct()

or with .exclude(..):

News.objects.exclude(channels=None)
like image 183
Willem Van Onsem Avatar answered Sep 27 '22 20:09

Willem Van Onsem