【问题标题】:Loading dynamic model attributes in the form - django以表单加载动态模型属性 - django
【发布时间】:2016-12-15 10:55:42
【问题描述】:

所以我正在构建一个广告应用。 基本上,用户登录后,就可以发布广告。 我已经发布了下面的模型,但基本上我有一个类别(例如,电子产品或房地产),然后是一个子类别(电子产品->笔记本电脑或房地产->房屋、公寓等) 问题是,不同的物品有不同的属性。 例如,笔记本电脑可能具有“屏幕”、“内存”和“硬盘”属性,而“汽车”可能具有“里程”和“状况”。 我决定将这些属性存储在 JSONField 中。

from django.db import models
from django.contrib.postgres.fields import JSONField

class Category(models.Model):
    name = models.CharField(max_length=255)

def __str__(self):
    return self.name

class SubCategory(models.Model):
    category = models.ForeignKey('Category')
    name = models.CharField(max_length=255)

def __str__(self):
    return self.name


class Product(models.Model):
    name = models.CharField(max_length=255)
    subcategory = models.ForeignKey('SubCategory')
    description = models.TextField()
    price = models.IntegerField()
    price_fixed = models.BooleanField(default=False)
    monthly_payments = models.BooleanField(default=False)
    created = models.DateField(auto_now_add=True)
    custom_attributes = JSONField(default=dict)


def __str__(self):
    return self.name

现在,如何处理表单和视图中的这些自定义属性? 我需要这样做,以便当用户从下拉列表中选择类别/子类别时,这些属性需要显示为文本字段,并且用户将输入屏幕尺寸、T 恤尺寸或颜色等。

这是我的第一个 django 应用程序,我从中学到的书没有涵盖这样的内容,我不确定从这里去哪里,在 google/SO 上搜索并没有找到解决方案。

【问题讨论】:

    标签: python django django-forms django-views


    【解决方案1】:

    JSONFields 适用于 Python 不会经常自省的结构化元数据。

    在您的情况下,我建议为字段配置创建另一个表,将此表链接到类别,并为产品中的值创建一个表。简化形式:

    class CategoryAtrribute(models.Model):
        name = models.CharField()
        value_type = models.CharField()
    
    
    class Category(models.Model):
        attributes = models.ManyToManyField(CategoryAtrribute)
    
    
    class AttributeValues(models.Model):
        category = models.ForeignKey('Category')
        attribute = models.ForeignKey('CategoryAtrribute')
        value = models.TextField()
    
    
    class Product(models.Model):
        attribute_values = models.ManyToManyField(CategoryAtrribute, through=AttributeValues)
    

    这里的问题基本上有两个: 1.您需要确保产品仅具有其类别允许的属性 2.检查字段类型的函数需要硬编码

    此解决方案的一个更简单的版本是创建一个表元数据,其中包含所有类别的所有可能字段。此模型将包含 one2one 和产品,类别将包含要使用的字段列表。

    【讨论】:

    • value_type 应该放入什么样的数据?
    • 该字段中存储的值的类型——字符串、整数等
    • 只有当你想用这个值做一些事情时才重要(例如,检查哪辆车最重)。如果您只想按此值存储/过滤,则可以不使用value_type
    • 花了我一段时间,但我想我明白了(整个解决方案):) 有没有办法从产品类中访问属性值?现在我可以像这样访问值:>>> AttributeValues.objects.get(product=p1),其中 p1 是 Product 对象。
    • 我现在看到AttributeValues 类中有一个错误。它应该是:product = models.ForeignKey('Product') 而不是类别。您可以通过以下方式访问产品中的值:product.attributevalues_set
    猜你喜欢
    • 2023-03-27
    • 2018-06-27
    • 2016-03-17
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    相关资源
    最近更新 更多