首页 > 解决方案 > 当产品只是属性类中的外键时,如何创建产品过滤器?(Django电子商务)

问题描述

我正在尝试创建一个产品过滤器来过滤产品属性(例如这个例子),但我有几个问题:

我的产品的属性被间接定义为ProductAttributesValue 类中的外键,它将产品和属性键连接到属性值,即:


class ProductAttributes(models.Model):
    """
    The Product Attributes Table contains product attributes
    or features for the product category.
    """

    product_category = models.ForeignKey(ProductCategory, on_delete=models.RESTRICT)
    name = models.CharField(max_length=255)

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

class Product(models.Model):  # models.Model
    """
    Product Table
    """

    title       = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    aff_link    = models.URLField(default="https://designerstuen.dk/")
    image       = models.FileField(null=True, blank=True, upload_to='static/images') #, default='static/images/product-default.png')
    merchant    = models.CharField(max_length=150)
    regular_price = models.DecimalField(
        verbose_name = "Regular price",
        decimal_places = 2,
        max_digits = 1000
        )
    discount_price = models.DecimalField(
        verbose_name = "Discount price",
        decimal_places = 2,
        max_digits = 1000,
        null=True,
        blank=True
        )
    created_at = models.DateTimeField(
        verbose_name = "Created at",
        auto_now_add = True,
        editable = False
    )
    updated_at = models.DateTimeField(
        verbose_name = "Updated at",
        auto_now = True
    )

    categories = TreeManyToManyField('ProductCategory') # on_delete=models.CASCADE, null=True, blank=True   

    class Meta:
        ordering = ("-created_at",)
        verbose_name = "Product"
        verbose_name_plural = "Products"

    def get_absolute_url(self):
        #return f"/products/{self.id}/"
        return reverse("products:product_detail", kwargs={"id": self.id})


class ProductAttributesValue(models.Model):
    """
    The Product Attributes Value Table holds each of the product's
    individual attributes or features.
    """

    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    attribute = models.ForeignKey(ProductAttributes, on_delete=models.RESTRICT)
    value = models.CharField(
        verbose_name = "value",
        max_length = 255
    )

现在,我只是在每个产品类别页面上显示所有相关产品。尚未使用含义属性。

  1. 当产品属性没有直接在产品类中定义为模型字段时,我如何在产品类别页面上创建产品属性过滤器?

  2. 这甚至是设置产品属性的最佳方式吗?(类别是使用MPTT设置的,我通过在线指南找到了这个属性实现)。

  3. 一个重要的注意事项是我希望产品过滤是“硬 URL”,意思是 /red/ 而不是 ?color=red。这需要过滤中的某种层次结构,因为不能有重复的 URL(例如:/red/hugo-boss 和 /hugo-boss/red)。

谢谢!

标签: djangodjango-modelsdjango-viewsdjango-templates

解决方案


推荐阅读