我想在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)。我只是不知道會彈出什麼,所以我試圖儘可能通用。