简体   繁体   English

使用反向外键查找的Django ListView

[英]Django ListView using reverse foreignkey lookup

If I have code as follows: 如果我有如下代码:

Person

Email
  FK(Person)

Phone
  FK(Person)

Address
  FK(Person)

And I want to display a ListView with each person and a phone number, email and address for each of them, all()[0] is good enough, how would I go about creating a QuerySet to pass into ListView? 而且我想显示每个人的ListView以及每个人的电话号码,电子邮件和地址,all()[0]足够好,我将如何创建一个QuerySet传递给ListView?

Thanks 谢谢

Are the relations one-to-one or one-to-many? 关系是一对一还是一对多? If one-to-one, you can get all references in a single query using Django's aggregation features. 如果是一对一的,则可以使用Django的聚合功能在单个查询中获取所有 引用 (Edit: sorry, not the references, only their pks) For instance: (编辑:对不起,不是引用,只有它们的pk)例如:

from django.db.models import Min
Person.objects.all().annotate(email=Min('email'), phone=Min('phone'), address=Min('address'))

I don't know whether it will integrate well with ListView, though... Maybe using OneToOneField will work in this case (even without the aggregation), I'm not sure. 我不知道它是否可以与ListView很好地集成,但是...也许在这种情况下(即使没有聚合)也可以使用OneToOneField ,但我不确定。

If the relations are one-to-many, I'm afraid you won't be able to do that in a single query. 如果关系是一对多的,恐怕您将无法在单个查询中做到这一点。 As you probably know already, given a Person object you can get the related models using the _set suffix: email_set , phone_set and address_set . 您可能已经知道,给定Person对象,您可以使用_set后缀获取相关模型: email_setphone_setaddress_set But to access them, you'd need other queries (more database hits). 但是要访问它们,您将需要其他查询(更多数据库命中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM