我想在Django中创建用户配置文件应用程序(我知道有一些存在,谢谢),我想知道如何构建模型以允许任意组合字段在每个子部分。例如,“教育”一节可能有一个名为“编程体验”的小节,“个人信息”一节可能有一个小节叫做“最爱”。Django:结构Django模型允许任意字段类型
按照典型的侧栏导航设置思考,每个部分都是一个标题,每个子部分都将链接到可以操作信息的表单。
Education
- Schooling
- Programming Experience
Personal Info
- Location
- Favourites
- Look a-likes
我想要做的是能够将项目添加到任意基础上的子部分。无论网站的感受如何。
也许一个网站会从用户上过的学校照片中受益,而另一个网站可能只需要一个描述。
我想使用管理界面将这些字段类型添加到子部分。因此,添加一个项目将呈现它是什么类型的信息(图像,视频,文本等)的选择以及要应用于哪个子部分。
我想知道你会如何做到这一点;更重要的是,尽可能少地跳过。
谢谢。
编辑:
怀着希望去澄清这个问题,我会提供一个样本models.py文件。这只是一个快速提升,以更准确地展示问题。我有两个解决方案,我认为解决方案二将比解决方案更好;但我也想在这里看看SO社区的想法,以及他们是否有其他解决方案。
**models.py**
class Section(models.Model):
"""
The root of categorization. Acts much like a header
"""
name = models.CharField(max_length=30)
description = models.CharField(max_length=255)
class SubSection(models.Model):
"""
The contents of each section. Contains many items of varying types as needed
by the site developer.
"""
name = models.CharField(max_length=30)
description = models.CharField(max_length=255)
section = models.ForeignKey(Section)
class Item(models.Model):
"""
I would like this to store the information here and have a foreign key to the
'SubSection' table. The problem is that there are a lot of different information
types that can be stored and I'd need a row for each type. Thus for each
entry most of the columns will be blank.
I'm thinking that it may be better to use this table as a pointer to another
table that actually contains the information. This will result in a lot of
tables but will eliminate waste.
"""
name = models.CharField(max_length=30)
description = models.CharField(max_length=255)
sub_section = models.ForeignKey(SubSection)
### Solution One
# Storing the info here results in a lot of wasted space and may not be all
# that flexible
image = models.ImageField()
text = models.CharField(max_length=255)
numeric = models.IntegerField()
time = models.TimeField()
# etc ...
### Solution Two
# Storing the field info results in more tables but allows for a better match
# of information and field type.
field_type = models.CharField(max_length=255)
field_properties = models.CommaSeparatedIntegerField(max_length=None)
### Solution Two Tables
# Solution two would require a table for each field type supported here, which
# is quite a few different types.
class ImageStorage(models.Model):
item = models.ForeignKey(Item)
information = models.ImageField()
class IntegerStorage(models.Model):
item = models.ForeignKey(Item)
information = models.IntegerField()
### etc ...
请记住它是针对用户配置文件的。因此,减肥网站可能希望用户在个人资料中的当前体重(数字信息),而旅行网站可能需要访问过的地方列表(文本信息,甚至可以使用IPAddressField)。我只是不知道会弹出什么,所以我试图尽可能通用。