2013-07-17 96 views
3

我是Django中的新成员,我正在给自己一个试图构造此查询的大头盔。在Django中使用通过多对多关系进行查询

  • 我有一个BaseProfileOneToOne字段连接到用户
  • 我专业的个人资料CustomerProfileOneToOne场连接到BaseProfile
  • CustomerProfile与其他CustomerProfile(因此本身)通过一个RelatedCustomer模型多对多关系
  • RelatedCustomer我指定的from_customerto_customer外键



也许你可以更好地理解图像。

enter image description here

我的问题
给定一个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 = 2TestCustomer4

[<CustomerRelated: from TestCustomer4 to TestCustomer2 >, 
<CustomerRelated: from TestCustomer4 to TestCustomer3 >] 

:ACK类似。

我的问题:

到目前为止好,但现在有这个设置我怎样才能得到所有user.id的to_customer
也就是说,如何获取user.idTestCustomer2TestCustomer3

+0

请检查是否该为你工作。 –

+0

@GamesBrainiac感谢您的回答。我已经使用了你的链接和建议,但我仍然没有明白。我编辑了我的问题,添加了与我需要执行的操作相同的SQL。 – Leonardo

+0

看看你是否可以用原始SQL做到这一点。我会尝试在django ORM中给你解决方案,但即使是我的ORM技能也不是那么好。 –

回答

0

好吧,像往常一样,只要你得到答案,它总是比你期望的更容易。

我想这个工作对我来说:

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

非常感谢@Games智囊团

4

首先,这不是你如何在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")。表格的名称通常是<app>_<model>

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