【发布时间】:2023-04-07 12:47:01
【问题描述】:
我想为产品及其属性使用自定义中间表。我定义了以下模型,
class Products(models.Model):
name = models.CharField(max_length=600, blank=True)
brand = models.CharField(max_length=300, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Attributes(models.Model):
name = models.CharField(max_length=600)
product = models.ManyToManyField(Products, through="AttributesMapping", related_name="attributes")
class AttributesMapping(models.Model):
attribute = models.ForeignKey(Attributes)
product = models.ForeignKey(Products)
value = models.TextField(blank=True)
在视图中将产品对象添加到上下文和从模板尝试通过说来获取属性
{% for attribute in product.attributes.all %}{{ attribute.name }}: {{ attribute.value }} {% endfor %}
我正在获取名称,但未显示该值。我尝试检查正在执行的 sql 语句。
SELECT `attributes`.`id`, `attributes`.`name` FROM `attributes` INNER JOIN `attributes_mapping` ON (`attributes`.`id` = `attributes_mapping`.`attribute_id`) WHERE `attributes_mapping`.`product_id` = 1
值在“attributes_mapping”表中,Select 语句有引用但没有选择该字段。
提前感谢您的任何帮助或建议。
【问题讨论】:
-
请显示创建查询集的代码。那里可能有问题。
-
在视图中我只是这样做
product = Products.objects.get(url=product_url)和return render('template.html', {product: product})
标签: python django django-models django-templates