Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用自定义中间表的Django-ManyToMany关系查询集_Python_Django_Django Models_Django Templates - Fatal编程技术网

Python 使用自定义中间表的Django-ManyToMany关系查询集

Python 使用自定义中间表的Django-ManyToMany关系查询集,python,django,django-models,django-templates,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 = model

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

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
该值位于“属性映射”表中,Select语句具有引用,但未选择该字段


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

请记住,
属性
上没有定义
,而是在直通表中定义的。要访问它,您需要访问属性映射对象:

或者:

for attribute in product.attributes.all():
    mapping = attribute.attributemapping_set.get(product=product)
    print attribute.name, mapping.value

这当然意味着您必须改变您的操作方式,因为django模板不支持此类函数调用。如果不了解更多有关设置的信息,我就无法真正建议如何最好地执行此操作。

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

请显示创建查询集的代码。这可能是有问题的。在视图中,我只是这样做
product=Products.objects.get(url=product\u url)
return render('template.html',{product:product})
for attribute in product.attributes.all():
    mapping = attribute.attributemapping_set.get(product=product)
    print attribute.name, mapping.value