Django ManyToMany关系QuerySet使用自定义中间表

时间:2013-03-15 18:07:09

标签: python django django-models django-templates

我想为产品及其属性使用自定义中间表。我定义了以下模型,

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)

在视图中将Products对象添加到上下文中,并从模​​板中尝试通过说

来获取属性
{% 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语句有引用但没有选择该字段。

提前感谢您的任何帮助或建议。

2 个答案:

答案 0 :(得分:0)

请注意,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模板不支持这些函数调用。如果不了解您的设置,我无法真正建议如何做到最好。

答案 1 :(得分:0)

您在模板中获得Attribute个对象({% for attribute in product.attributes.all %}),但使用它就像拥有AttributesMapping个对象一样。 Attribute对象没有value属性。

相关问题