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

San*_*San 5 python django django-templates django-models

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

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)
Run Code Online (Sandbox Code Playgroud)

在视图中将 Products 对象添加到上下文并从模板中尝试通过说来获取属性

{% for attribute in product.attributes.all %}{{ attribute.name }}: {{ attribute.value }} {% endfor %}
Run Code Online (Sandbox Code Playgroud)

我得到了名称,但值没有显示。我尝试检查正在执行的 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
Run Code Online (Sandbox Code Playgroud)

该值在“attributes_mapping”表中,Select 语句有一个引用但未选择该字段。

在此先感谢您的任何帮助或建议。

Ham*_*mms 1

请记住,它value不是在 上定义的attribute,而是在 through 表上定义的。为了访问它,您需要访问属性映射对象:

for mapping in AttributesMapping.objects.get(product=product):
    print mapping.attribute.name, mapping.value 
Run Code Online (Sandbox Code Playgroud)

或者:

for attribute in product.attributes.all():
    mapping = attribute.attributemapping_set.get(product=product)
    print attribute.name, mapping.value
Run Code Online (Sandbox Code Playgroud)

这当然意味着您必须改变做事的方式,因为 django 模板不支持此类函数调用。如果不了解您的设置,我无法真正建议如何最好地做到这一点。