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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With