【问题标题】:Django ManyToMany relation QuerySet using custom intermediate table使用自定义中间表的 Django ManyToMany 关系 QuerySet
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    请记住,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 模板不支持这类函数调用。在不了解您的设置的情况下,我真的无法建议如何最好地做到这一点。

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 2012-03-14
      • 2016-08-20
      • 2018-01-21
      相关资源
      最近更新 更多