繁体   English   中英

无法使用 Django 中的外键访问相关的 model 数据

[英]Not able to access related model data using foreign key in Django

模型.py

class products(models.Model):
    name = models.CharField(max_length=100)
    sku = models.CharField(max_length=50)
    vendor = models.CharField(max_length=50)
    brand = models.CharField(max_length=50)
    price = models.FloatField()
    product_status = models.BooleanField()
    quantity = models.IntegerField()

    def __str__(self):
        return self.name


# categories
class categories(models.Model):
    category_name = models.CharField(max_length=50)
    parent_id = models.IntegerField()


# product categories
class product_categories(models.Model):
    product = models.ForeignKey(products, on_delete=models.CASCADE)
    category = models.ForeignKey(categories, on_delete=models.CASCADE)

    def __str__(self):
        return self.category
  1. 我可以使用访问“类别”表数据(在 django 外壳内)
data = products.objects.all()
data.values('product_categories__category__category_name')
output: <QuerySet [{'product_categories__category__category_name': 'xxxx'}}]>
  1. 如果我把这个(在 django 外壳内)
data.product_categories.category
output: 'QuerySet' object has no attribute 'product_categories'

如何获得一个查询集(可以传递给 html),其中包括来自“类别”表的数据以及“产品”表的数据

这里发生了几个问题。 首先, data是一个查询集,它有点像一个对象列表,尽管列表中只有一个 object。 您想要的是从列表中的项目中获取一个属性,因此您需要类似data.first()的东西来获取该 object ,然后再开始添加它的属性。

其次,Django 处理反向 FK 关系的方式要求您通过标准名称(在您的情况下为product_categories_set )引用 FK,或者您在 FK 上设置自己的related_name属性。 就像是:

# product categories
class product_categories(models.Model):
    product = models.ForeignKey(products, on_delete=models.CASCADE, related_name='product_categories')
    category = models.ForeignKey(categories, on_delete=models.CASCADE, related_name='product_categories')

    def __str__(self):
        return self.category

这样您就可以仅使用data.product_categories从产品和类别中引用您的 product_categories model 。

第三,当访问反向FK关系时,就像上面第(1)点一样,你会得到一个相关的manager,从中你可以得到一个queryset of items。 因此,要获取类别名称,您需要指明您想要类别名称的项目。 假设它只是所有东西的第一项,它看起来像:

data = products.objects.all()
product_category = data.product_categories.all()
category_name = product_category.category.category_name

当然,一旦您拥有更多数据,您不会总是只想选择第一个项目,因此您需要在查询中添加过滤逻辑以确保您获得所需的项目。

ETA,我同意上面 Jorge 的评论 - MTM 会使这更简单一些,并且本质上会为您创建您的 product_categories 表。

暂无
暂无

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

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