因此,我正在构建一个广告应用程序。基本上,用户登录后,他们可以发布有关某事的广告。我在下面发布了模型,但基本上我有一个类别(例如,电子产品或房地产),然后是一个子类别(电子产品->笔记本电脑或房地产->房屋,公寓等)。问题是,不同的物品具有不同的属性。例如,一台笔记本电脑可能具有“屏幕”,“ 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上搜索并没有找到解决方案。
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,类别将具有从中使用的字段列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句