一种方法是创建一个包含所有公共属性的“主”表,并为每种类型的对象创建单独的表。这在 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.
优点:
- 类定义看起来简洁明了。
- 非常接近最佳数据库结构。
- 一个数据库查询可以检索各种类型的项目。
缺点:
- 检索具有完整数据的对象时连接过多。