I have these 2 models in a Django app:
class Tag(models.Model):
name = models.CharField(max_length=100, blank=False, unique=True)
class Article(models.Model):
title = models.CharField(max_length=100, blank=True, default='')
tags = models.ManyToManyField(Tag, blank=True)
In my views, I'd like to filter the articles and only get the articles where articles.tags
contains the tag with id == 2
. How can I do that ?
I tried
tags = Tag.objects.filter(pk=2);
articles = Article.objects.filter(len(tags) > 0)
but I have this error 'bool' object is not itterable
.
Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this. Adding a FilterSet with filterset_class. Using the filterset_fields shortcut.
A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.
This is the correct way of filtering manytomany in django
articles = Article.objects.filter(tags__in=[2])
or
tags = Tag.objects.filter(pk=2)
articles = Article.objects.filter(tags__in=tags)
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