在表单中加载动态模型属性 - django

时间:2016-08-09 11:53:02

标签: python django django-forms django-views

所以我正在构建一个广告应用。 基本上,用户登录后,他们可以发布广告。 我已经发布了下面的模型,但基本上我有一个类别(比如电子产品或房地产),然后是一个子类别(电子产品 - >笔记本电脑或房地产 - >房子,公寓等) 问题是,不同的项目具有不同的属性。 例如,笔记本电脑可能具有“屏幕”,“ram”和“hdd”属性,而“汽车”可能具有“里程”和“条件”。 我决定将这些属性存储在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上搜索并没有找到我的解决方案。

1 个答案:

答案 0 :(得分: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 with product和Category将包含要使用的字段列表。