我想在Django
中创建一个条目表。问题是每个项目都有不同的内部结构,我不得不创建太多的表。
例如,如果item是CPU
,那么我希望内部结构属性(列)如下所示:
type:processor
frequency:value
number of cores:value
socket:value
如果该项目为smartphone
,则其内部结构如下:
type:smartphone
os:value
displaysize:value
cpuID:value
在向数据库中添加新项时,字段应首先询问用户他希望添加的类型(例如CPU),并根据此信息显示取决于类型的内部结构属性的适当形式。内部结构的某些字段是必需的,但大多数字段是可选的,有些字段可以是多个的(例如,多个URL)。
实现这一点的方法是什么?对于这样的数据,Django
中已经有一些帮助了吗?各种方法的优缺点是什么?到目前为止,我看到了一个缺点。注意,智能手机使用cpuID作为外键。有可能保存参考资料吗?请注意,CPU可以引用它的制造商(只是一个例子,各种项目可以有几个对其他项目的引用)。
发布于 2013-09-06 17:57:57
一种方法是为每种类型的对象创建一个具有所有公共属性和单独表的“主”表。在Django中这样做非常容易,模型定义看起来“干净”,有关详细信息,请参阅多表继承。
用于您的情况的示例模型:
# Hold common fields/properties
class Item(models.Model):
type = ...
price = ...
weight = ...
width = ...
height = ...
...
# Below are example classes which will inherit all properties from Item
class CPU(Item):
frequency = ...
core_count = ...
socket = ...
class Smartphone(Item):
os = ...
display_size = ...
cpu = models.ForeignKey(CPU, ...) # Example linking between items.
请注意,每个“具体”项由两个数据库行组成:公共表和“具体”表中。这两个表在“具体”表中由一个一对一的字段连接(Django为您添加了这个字段,但如果需要,您可以重新定义它)。
从数据库检索项的示例方法:
# Get all "base" items without touching type tables
Item.objects.all()
# Get all items along with their child properties. This is rather ugly and expensive.
Item.objects.select_related('cpu', 'smarthphone', ...).all()
# Gets smartphones, uses a join to retrieve data from two tables.
# I don't remeber if the `select_related` is required here.
Smartphone.objects.select_related('item').all()
# When type of the item is only know at runtime, you can query like this (requires additional table column for storing type):
Item.objects.filter(type='smartphone')
# Or alternatively finding out which type class you want.
优势:
缺点:
https://stackoverflow.com/questions/18646230
复制相似问题