Django ManyToMany 关系使用自定义中间表的 QuerySet
我想为产品和它的属性使用自定义的中间表。我已经定义了以下模型,
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'表中,选择语句有引用,但没有选择那个字段。
提前感谢任何帮助或建议。
2 个回答
0
你在模板中得到了一个Attribute
对象({% for attribute in product.attributes.all %}
),但是你把它当成了一个AttributesMapping
对象来用。其实,Attribute
对象是没有value
这个属性的。
1
请记住,value
这个东西并不是在 attribute
上定义的,而是在一个中间表上定义的。要想访问它,你需要去访问属性映射对象:
for mapping in AttributesMapping.objects.get(product=product):
print mapping.attribute.name, mapping.value
另外:
for attribute in product.attributes.all():
mapping = attribute.attributemapping_set.get(product=product)
print attribute.name, mapping.value
这当然意味着你需要改变一下你的做法,因为这种函数调用在 Django 模板中是不支持的。如果不了解你具体的设置,我也很难给出最佳的建议。