如何反向查询OnetoOne Django

时间:2016-05-19 07:08:50

标签: python django

我有以下关系:

class Invoice(models.Model):
    customer = models.OnetoOneField('Customer')
    """ Other stuff """

class Customer(models.Model):
    name = models.CharField()
    """ Other stuff """

我的问题是:

如果我进行查询,请说:

inv_q = Invoice.objects.filter(date=today())

如何从此查询中获取所有相关客户?

cus_q = Customer.objects.filter(id__in=inv_q.customer)

我是否必须为此创建客户经理?

编辑1:

我正在生成一个必须包含这两个信息的report.json文件。为了不打算访问数据库并获取所有客户,我希望获得所选发票客户的信息。

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

cus_q = Customer.objects.filter(invoice__in=inv_q)

或直接使用field lookup

cus_q = Customer.objects.filter(invoice__date=today())

答案 1 :(得分:1)

您尝试做什么并不合理,您可以使用字段查找按发票日期过滤客户

Customer.objects.filter(invoice__date=today())

这似乎是最合适的

否则,您可以使用select_related预先检索每张发票的客户模型,然后在通过invoice_instance.customer进行访问时,将无法再查询

Invoice.objects.filter(date=today()).select_related('customer')