Home > Enterprise >  Filter field M2M in Django ORM
Filter field M2M in Django ORM

Time:07-02

My models:

class Tag(models.Model):
    tag_name = models.CharField(
        'Tag Name',
        max_length=255,
        null=True
    )

class Book(models.Model):
    name = models.CharField(
        'Name',
        max_length=255,
        null=True
    )
    tag = models.ManyToManyField(
        'Tag',
        related_name='tags',
        blank=True
    )

I wont filtering Book's model. In db i have several rows:
Tag
| id | name |
|-----|------|
| 1 |tag_1 |
| 2 |tag_2 |
| 3 |tag_3 |

Book
| id | name | tags |
|-----|-------|------|
| 1 |book_1 |tag_1|
| 2 |book_2 |tag_2|
| 3 |book_3 |tag_3|
| 4 |book_4 |tag_1, tag_2, tag_3|
How can i filtering book models, if i take new model Book with tag=tag_1, tag_2 and i want find in Book models all model with tag include tag_1 or tag_2. I want get queryset like this(for tag=tag_1, tag_2):

[(id=1, name=book_1), (id=2, name=book_2), (id=4, name=book_4)]

CodePudding user response:

If I understand your question you have a book_5 which has tags of tag_1 and tag_2 and you want to filter books based on book_5 tags.

you can use value_list you can turn your tags queryset into a list of IDs and then filter you books based on that. so it would be:

    book_5 = Book.objects.get(name='book_5')
    has_book_5_tags = Book.objects.filter(tag__id__in=book_5.tag.all().values_list('id',flat=True))
  • Related