3

我是 Django 的新手,尝试构建这个查询让我很头疼。

  • 我有一个BaseProfileOneToOne字段连接到User
  • 我正在将CustomerProfile中的配置文件与OneToOne字段连接到BaseProfile
  • CustomerProfile通过RelatedCustomer模型与其他CustomerProfile(本身)具有多对多关系。
  • RelatedCustomer 中,我指定了from_customerto_customer 外键



也许通过图像您可以更好地理解。

在此处输入图像描述

我的问题
给定一个 user.id 我需要知道他所连接的客户的所有其他 user.id(因此通过from_customerto_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
TestCustomer2TestCustomer3

4

2 回答 2

5

首先,这不是您在 django 中查询数据库的方式。其次(因为你正在学习),最好指出你可以跑去dbshell尝试不同的东西。最后,文档中描述了这种问题。

我告诉你这个,因为作为一个初学者,我也觉得通过整个事情有点难以驾驭。找东西的最好方法就是使用 google,并在最后添加一个django

我知道你的感受,文档搜索很糟糕,对吧?呵呵,我感觉到你了,所以你总是按照我描述的方式去寻找。一旦你掌握了文档,你会觉得文档标题页更直观一些。

好的,现在回答:要访问ManyToMany,OneToOneForeignKey字段,您需要使用__通常称为dunder

所以,这就是要做的事情。请注意,还有其他方法,并且可能是更好的方法:

thing_I_want = RelatedCustomer.objects.get(to_customer__id=2)

但是请注意,如果您想获取客户列表,您将使用filter(). 这是一个示例(以购买次数为例):

things_I_want = RelatedCustomer.objects.filter(to_customer__no_of_purchases=16)

另请注意,过滤器的好处在于您可以将一个过滤器堆叠在另一个过滤器之上。您可以在我在下面提供的文档链接中阅读有关这些功能的更多信息。

这会让你得到你想要的。现在,您可能对此有更多疑问,以及它们如何协同工作。不要害怕,请单击此文档链接查看。

编辑 似乎你想做的事情可以通过 django 来完成,但如果你想使用 sql 来完成,那么这也是可能的。例如,SomeModel.objects.raw("SQL_HERE")。表的名称通常是<app>_<model>.

但是,您所要求的也可以在 django 中使用 ORM 完成。但这会很棘手。

于 2013-07-17T06:44:06.540 回答
0

好的,像往常一样,每当您得到答案时,它看起来总是比您预期的要容易得多。

我想这对我有用:

User.objects.filter(base_profile__customer_profile__to_customer__in=
User.objects.get(id=2).base_profile.customer_profile.from_customer.all())

非常感谢@Games Brainiac

于 2013-07-19T02:02:40.417 回答