【发布时间】:2020-11-07 22:16:26
【问题描述】:
我的模型中定义了两个表:
class Products(models.Model):
productsid = models.AutoField(primary_key=True)
product_number = models.CharField(db_index=True, max_length=15)
title = models.CharField(max_length=255, default=None, null=True, blank=True)
date = models.DateField(db_index=True, default=datetime.date.today, null=True, blank=True)
class ProductFlag(models.Model):
product_number = models.CharField(db_index=True, max_length=15)
company = models.ForeignKey(Company, db_index=True, on_delete=models.SET_NULL, null=True)
productid = models.ForeignKey(Products, db_column='productsid', db_index=True, on_delete=models.SET_NULL, null=True)
我想在查询 ProductFlag 时从 Products 中获取“标题”。
在我看来,我提出了这个问题:
productflags = ProductFlag.objects.filter(company__companyid=self.kwargs.get('company_id')).order_by('product_number')
我认为我可以通过循环 {% for product in productflags %} 来引用模板中的标题字段,然后 抓住 {{ product.productid.title }},但我什么也没得到。在 Django shell 中查看它,似乎我的 productid 始终为“None”(而且我的数据库中肯定有 productsid 中的数据)。我对公司外键没有任何问题。我做错了什么?
抱歉,我有一个错字。我在模板的循环内引用 product.productid.title; product_number 错误。我也仔细检查了我的数据库,所有引用的字段都有数据。
我不知道这会有所帮助,但在 django shell 中我得到了这种行为:
testflags = ProductFlag.objects.filter(company__companyid=43).order_by('product_number') 获得大约七个查询集。如果我然后尝试访问 testflags[0].company.companyname,我会得到实际的公司名称。另一方面,如果我尝试访问 testflags[0].productid.title,我会得到“AttributeError: 'NoneType' object has no attribute 'title'”。
另外,如果我尝试“testflags = ProductFlag.objects.select_related('productid').filter(company__companyid=43).order_by('product_number')”,查询会看到 Products 中的列名,但使用 productid 访问它们,给出 AttributeError。
在 pgAdmin 中,这个查询工作得很好:
SELECT a.product_number, b.title
FROM productflag AS a
INNER JOIN products AS b
ON a.product_number = b.product_number
AND a.company_id = 43;
谢谢--
阿尔
【问题讨论】:
标签: django