简体   繁体   中英

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']

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')

与标准Model.objects()一样,“多对多”字段为您提供了一个经理,您可以使用完全相同的方式对其进行过滤:

related_entity.filter(entity_type__entity_type_label="MAMMAL")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM