【问题标题】:Query on a Many to Many relationship using through in Django在 Django 中使用 through 查询多对多关系
【发布时间】:2013-07-15 11:14:05
【问题描述】:

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

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



也许用一张图片你可以更好地理解。


我的问题
给定一个 user.id,我需要知道他所连接的客户的所有其他 user.id(所以通过from_customerto_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
即如何获取TestCustomer2TestCustomer3user.id

【问题讨论】:

  • 请检查这是否适合您。
  • @GamesBrainiac 感谢您的回答。我已经使用了您的链接和建议,但我仍然不明白这一点。我已经编辑了我的问题,添加了与我需要做的等效的 SQL。
  • 看看你是否可以在原始 SQL 中做到这一点。我会尝试在 django ORM 中为您提供解决方案,但即使是我的 ORM 技能也不是那么好。
  • 我只想对您在问题中所做的努力表示感谢。我可能无法回答,但我会投赞成票,因为您已努力使您的问题清楚。
  • 编辑了,看看吧。

标签: django django-models django-queryset django-orm


【解决方案1】:

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

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

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

好的,现在回答: 要访问ManyToManyOneToOneForeignKey 字段,您需要使用通常称为dunder__

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

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

但请注意,如果您想获取客户列表,请使用filter()。下面是一个例子(以购买次数为例):

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

    我想这对我有用:

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

    非常感谢@Games Brainiac

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 2021-03-07
      • 2015-10-26
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 2013-11-22
      • 2011-11-13
      相关资源
      最近更新 更多