Django ORM处理多个多对多关系的方式 [英] Django ORM way of going through multiple Many-to-Many relationship
问题描述
亲爱的人们试图帮助他人,
Dear people trying to help others,
我正在尝试弄清楚如何让Django在不编写自定义SQL的情况下为我做连接。
I am trying to figure out how to get Django to do a join for me without writing custom SQL.
假设我有以下模型
class Parent(models.Model):
name = models.CharField()
children = models.ManyToManyField(Child, through="Parent_Child", related_name="parents")
class Parent_Child(models.Model):
parent = models.ForeignKey(Parent, related_name='attached_children')
child = models.ForeignKey(Child, related_name='attached_parents')
class Child(models.Model):
name = models.CharField()
toys = models.ManyToManyField(Toy, hrough="Child_Toy", related_name="toy_owners")
class Child_Toy(models.Model):
child = models.ForeignKey(Child, related_name='attached_toys')
toy = models.ForeignKey(Toy, related_name='toy_owner')
class Toy(models.Model):
name = models.CharField
父母可以有多个孩子。一个孩子可以有多个父母。一个孩子可以拥有多个玩具。玩具可以由多个孩子拥有。
A parent can have multiple children. A child can have multiple parents. A child can own multiple toys. Toys can be owned by multiple children.
我想获得父母子女拥有的所有玩具的列表。
I want to get a list of all toys owned by a Parent's Children.
因此,我可以执行以下操作:
parent.children.all()
和 child.toys。 all()
So, I can do things like:
parent.children.all()
and child.toys.all()
我想做的事情就像 parent.children.toys.all()
尝试执行此操作时,得到: AttributeError:'ManyRelatedManager'对象没有属性'toys'
。我确实了解错误- parent.children
返回多个记录。这是预期的。我不知道是如何给Django提示,我希望它向其查询添加一个附加联接。
what I want to do is something like parent.children.toys.all()
When I try to do this I get: AttributeError: 'ManyRelatedManager' object has no attribute 'toys'
. I do understand the error - parent.children
returns multiple records. This is expected. What I can't figure out is how to give Django the hint that I want it to add an additional join to its query.
有没有办法做到这一点?加入Django还是我需要转到自定义SQL才能做到这一点?
Is there a way I can do this join within Django or do I need to go to custom SQL in order to do this?
请注意:以上内容只是为了说明我的问题,我使用的实际模型并不相关。我的问题实际上是试图弄清楚如何在Django中通过多个M2M关系加入而不必求助于SQL。
Please Note: The above is just meant to illustrate my issue, the actual models that I am using aren't that relevant. My issue is really trying to figure out how to join through multiple M2M relationships in Django without having to resort to SQL.
我非常感谢您的帮助。谢谢!
I appreciate your help in advance. Thanks!
推荐答案
只需编写以下内容:
Toy.objects.filter(toy_owners__parents=parent)
这篇关于Django ORM处理多个多对多关系的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!