我是 Django 的新手,尝试构建这个查询让我很头疼。
- 我有一个BaseProfile与OneToOne字段连接到User。
- 我正在将CustomerProfile中的配置文件与OneToOne字段连接到BaseProfile。
- CustomerProfile通过RelatedCustomer模型与其他CustomerProfile(本身)具有多对多关系。
- 在RelatedCustomer 中,我指定了from_customer和to_customer 外键。
也许通过图像您可以更好地理解。
我的问题:
给定一个 user.id 我需要知道他所连接的客户的所有其他 user.id(因此通过from_customer和 to_customer):
所以基本上,首先我需要使用反向查找从 User 挖掘到 RelatedCustomer ,获取所有集合,然后返回了解集合中每个客户 的user.id。
编辑2:
到目前为止我所达到的:
# 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()
这给了我类似的东西:
[<CustomerRelated: from TestCustomer4 to TestCustomer2 >,
<CustomerRelated: from TestCustomer4 to TestCustomer3 >]
在这种情况下,具有user.id=2的用户是TestCustomer4。
我的问题:
到目前为止一切都很好,但是现在有了这个设置,我怎样才能获得to_customer的所有 user.id?
也就是说,我如何获取and的user.id?TestCustomer2
TestCustomer3