[英]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. 假设我的模型中有一个多对多关系字段,如果实体中的字段等效于MAMMAL,我想做的就是获取所有相关实体。 I'm currently doing this in a list comprehension but wondering if there's a more elegant solution that django models provide. 我目前正在以列表理解的方式进行此操作,但想知道django模型是否提供了更优雅的解决方案。
[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: 根据Django文档( https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/ ),您可以使用:
entity.objects.filter(related_entity__entity_type__entity_type_label == 'MAMMAL') entity.objects.filter(related_entity__entity_type__entity_type_label =='MAMMAL')
与标准Model.objects()
一样,“多对多”字段为您提供了一个经理,您可以使用完全相同的方式对其进行过滤:
related_entity.filter(entity_type__entity_type_label="MAMMAL")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.