我是Django中的新成员,我正在给自己一个试图构造此查询的大头盔。在Django中使用通过多对多关系进行查询
- 我有一个BaseProfile与OneToOne字段连接到用户。
- 我专业的个人资料CustomerProfile与OneToOne场连接到BaseProfile。
- 甲CustomerProfile与其他CustomerProfile(因此本身)通过一个RelatedCustomer模型多对多关系。
- 在RelatedCustomer我指定的from_customer和to_customer外键。
也许你可以更好地理解图像。
我的问题:
给定一个user.id我需要知道的客户,他连接到(所以通过from_customer的所有其他user.id和to_customer):
所以基本上,首先我需要挖掘从用户到相关客户使用反向查找,完成所有设置,然后再回头了解该集合中每个客户的user.id。
EDIT2:
我到目前为止已经达到了:
# This gives me back a customer profile given a user.id (2)
cm = CustomerProfile.objects.get(base_profile__user=2)
# M2M lookup. Given one customer returns all the RelatedCustomer relations
# that he has as a part of the 'from' M2M
cm.from_photographer.all()
链接前两个:给定一个user.id我获得查询集 CustomerRelated关系:
rel = CustomerProfile.objects.get(base_profile__user=2).from_photographer.all()
这给了我b凡在这种情况下,用户具有user.id = 2是TestCustomer4
[<CustomerRelated: from TestCustomer4 to TestCustomer2 >,
<CustomerRelated: from TestCustomer4 to TestCustomer3 >]
:ACK类似。
我的问题:
到目前为止好,但现在有这个设置我怎样才能得到所有user.id的to_customer的?
也就是说,如何获取user.id的TestCustomer2
和TestCustomer3
?
请检查是否该为你工作。 –
@GamesBrainiac感谢您的回答。我已经使用了你的链接和建议,但我仍然没有明白。我编辑了我的问题,添加了与我需要执行的操作相同的SQL。 – Leonardo
看看你是否可以用原始SQL做到这一点。我会尝试在django ORM中给你解决方案,但即使是我的ORM技能也不是那么好。 –