Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11315

Django filter manytomany results

Say that I have a many to many relationship field in my model, what I'm trying to do is get all the related entities if the field in the entity is equivalent to MAMMAL. I'm currently doing this in a list comprehension but wondering if there's a more elegant solution that django models provide.

[related_entity for related_entity in related_entity.related_entities.all() if
                                  related_entity.entity_type.entity_type_label == 'MAMMAL']

Upvotes: 0

Views: 198

Answers (2)

M Nour
M Nour

Reputation: 37

Based on Django documentation(https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/), you could use:

entity.objects.filter(related_entity__entity_type__entity_type_label == 'MAMMAL')

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599946

A many-to-many field gives you a manager, just like the standard Model.objects() one, and you can filter it in exactly the same way:

related_entity.filter(entity_type__entity_type_label="MAMMAL")

Upvotes: 2

Related Questions