【发布时间】:2014-07-29 06:05:58
【问题描述】:
我想做的是一个数据库来跟踪个人记录。 模型快完成了,但我在存储不同类型的记录时遇到了一些困难。
有时间记录、重量记录、重复/圈数记录、距离记录……所以,数据有不同类型:时间、小数、整数……
起初我为每种类型的数据创建了一个表(或 django 中的类)。一个表到时间,其他到重量(十进制)等等。
但我想知道是否有更好的解决方案来只为所有记录保留一张表。
我的分隔表/模型的代码(因此,我为每种类型设置一个类,总共 5 个模型):(这很好,但我必须预先选择适当的模型才能插入数据。)
class PRWeight(model.Models): # there are PRDistance, PRLaps, PRHeight, PRTime
user = FK(User)
exercise = FK(Exercise)
date = datefield()
weight = decimalfield() # integer, integer, decimal, time
class Meta:
unique_together = [user, exercise, date,]
或者我可以做这样的事情,如果它很好或者有更好的解决方案:
class PR(models.Model):
user = FK(User)
exercise = FK(Exercise)
date = datefield()
metric = FK(Metric) # choose between time, weight, height...
# the aspect beeing mesured
record = # how can I call the right field type?
或者我可以用空白=True 替换其他五个字段的“记录”字段
class PR(models.Model):
user = FK(User)
exercise = FK(Exercise)
date = datefield()
metric = FK(Metric) # choose between time, weight, height, distance...
# the aspect beeing mesured
# not necessary in this approach
wheight = decimalfield(blank=True)
height = decimalfield(blank=True)
time = timefield(blank=True)
distance = integerfield(blank=True)
laps = integerfield(blank=True)
我正在寻找一个简单的解决方案。到目前为止,我倾向于选择最后一个示例,因为它是直截了当的,但是填写表单的用户可能会犯错误...
【问题讨论】:
-
创建一个包含所有相似数据的抽象模型,然后将每个模型的特定数据分开。您可以使用抽象模型或表继承,这取决于您的应用程序逻辑来定义最佳方式。
-
我不认为您应该担心表,除非您直接在数据库中工作。 Django 有一个非常好的 ORM,ORM 的主要方面是您不必查看数据库及其存储方式。只需创建一个漂亮的类层次结构来访问您的所有项目和模型,并让 ORM 决定它需要多少表来保存它们。
标签: python database django database-design model