获取产品属性及其值

2022-07-06 11:38:31 发布

您现在位置:Python中文网/ 问答频道 /正文

产品和产品属性表按以下方式设计

class Attribute(models.Model):
    name = models.CharField(max_length=30, unique=True)
    slug = models.SlugField(max_length=250, unique=True)

    class Meta:
        verbose_name = "Attribute"
        verbose_name_plural = "Attributes"

    def __str__(self):
        return self.name


class AttributeValue(models.Model):
    name = models.CharField(max_length=250)
    value = models.CharField(max_length=100, blank=True, default="")
    slug = models.SlugField(max_length=255)
    attribute = models.ForeignKey(
        Attribute, related_name="values", on_delete=models.CASCADE
    )

    class Meta:
        ordering = ("sort_order", "id")
        unique_together = ("slug", "attribute")

    def __str__(self) -> str:
        return self.name

    def get_ordering_queryset(self):
        return self.attribute.values.all()


class ProductAttribute(models.Model):
    product = models.ForeignKey(Product, related_name="attribute_product", on_delete=models.CASCADE, null=True)
    attribute = models.ForeignKey(
        AttributeValue, related_name="attribute_value_product", on_delete=models.CASCADE
    )

    class Meta:
        ordering = ("sort_order",)
        verbose_name = "Product Attribute"
        verbose_name_plural = "Product Attributes"

    def __str__(self):
        return f'{self.product.name} - {self.attribute.name}'

    def get_ordering_queryset(self):
        return self.product.attribute_product.all()


class ProductTypeAttributeValue(models.Model):
    product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE)
    attribute_value = models.ForeignKey(AttributeValue, on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.product_type.name} - {self.attribute_value.value}'

我可以通过执行以下操作获得特定产品的属性列表

attribute = models.ProductAttribute.objects.filter(product=product)

我可以得到属性值和属性名

for a in attribute:
   print(a.attribute.name, a.attribute.attribute.name)

这会给我

Small Size
Medium Size

但我不知道如何以下面的方式返回

attribute [
        {
        name: color,
        slug: color
        values [
            {
                id: 1,
                name: R,
                value: Red
            },
            {
                id: 2,
                name: G,
                value: Green
            }
        ]
    }
    ]

Tags: nameselfreturnvalueonmodelsdefattributeproductdeletelengthmaxclassforeignkeystr

热门问题