【发布时间】:2013-07-15 11:14:05
【问题描述】:
我是 Django 的新手,尝试构建这个查询让我很头疼。
- 我有一个 BaseProfile,通过 OneToOne 字段连接到 User。
- 我正在将 CustomerProfile 中的配置文件通过 OneToOne 字段连接到 BaseProfile。
- CustomerProfile 与其他 CustomerProfile(本身)具有 ManyToMany 关系通过 RelatedCustomer 模型。
- 在 RelatedCustomer 中,我指定 from_customer 和 to_customer 外键。
也许用一张图片你可以更好地理解。
我的问题:
给定一个 user.id,我需要知道他所连接的客户的所有其他 user.id(所以通过from_customer 和 to_customer):
所以基本上,首先我需要使用 reverse lookup 从 User 挖掘到 RelatedCustomer,获取所有集合,然后返回了解每个集合的 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 关系的 queryset:
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?
即如何获取TestCustomer2和TestCustomer3的user.id?
【问题讨论】:
-
请检查这是否适合您。
-
@GamesBrainiac 感谢您的回答。我已经使用了您的链接和建议,但我仍然不明白这一点。我已经编辑了我的问题,添加了与我需要做的等效的 SQL。
-
看看你是否可以在原始 SQL 中做到这一点。我会尝试在 django ORM 中为您提供解决方案,但即使是我的 ORM 技能也不是那么好。
-
我只想对您在问题中所做的努力表示感谢。我可能无法回答,但我会投赞成票,因为您已努力使您的问题清楚。
-
编辑了,看看吧。
标签: django django-models django-queryset django-orm