Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter many to many field in Django model

Tags:

python

django

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.

like image 420
rocketer Avatar asked Oct 12 '15 16:10

rocketer


People also ask

What is filter Django?

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.

What is ManyToManyField?

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.


1 Answers

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)
like image 184
Geo Jacob Avatar answered Sep 23 '22 06:09

Geo Jacob