【问题标题】:Django foreign key not getting dataDjango外键没有获取数据
【发布时间】: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


    【解决方案1】:

    来自您的 sn-p:

    {% for product in productflags %}
        {{ product_number.productid.title }}
    {% endfor %}
    

    看起来你引用了错误的变量名,因为在循环中,它被声明为product,但你继续使用product_number

    尝试将product_number 更改为product,反之亦然。

    【讨论】:

      【解决方案2】:

      编辑:根据新信息,您的查询的过滤器部分似乎有错字。试试company_id 而不是companyid

      .filter(company__company_id=43)
      

      我相信问题出在您的循环中。您需要使用

      访问标题
      {{ product.productid.title }}
      

      这是假设查询集包含一些数据。

      【讨论】:

        【解决方案3】:

        感谢大家。你让我更仔细地查看我的代码。似乎我的 ProductFlag 表没有正确填充 productid;所以它在与 Products 的外键关系中使用了一个空值...没有有效的键 = 没有有效的数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-27
          • 1970-01-01
          • 2015-04-11
          • 2021-01-13
          • 1970-01-01
          • 2021-10-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多