【发布时间】:2014-08-22 08:26:58
【问题描述】:
我是 Django 新手,对数据库知之甚少。
让我解释一下我的问题。 例如,我有两个模型——Person 和 Car(一个人可以拥有多辆汽车。)
class Person(models.Model):
name
username
password
#some more user attributes.
class Car(models.Model):
user = models.ForeignKey(Person)
car_name
car_price
#other car atrributes
目前我正在使用这样的模型,但有人告诉我你应该像下面这样使用 -
class Car(models.Model):
car_name
car_price
#other car atrributes
class Person(models.Model):
name
username
password
car = models.ForeignKey(Car)
#some more user attributes.
注意到反向关系了吗?从人到车或从车到人,我应该使用哪一个。
我知道我可以在 ForeignKey 字段中使用 related_name 值进行反向查找。我只是对效率、标准和其他方面的优势感到好奇。
PS:虽然我目前正在使用第一个并且它运行良好。
【问题讨论】:
-
您的第一个条件是正确的 -
Person有多个Cars。现在,在第二个用例中,Peron 只能有 1 辆车作为外键。建议您进行更改的人可能意味着ManyToManyField- 许多Person引用多个Car -
@karthikr :但我可以再创建一个汽车模型对象,并且同一个人也可以指向该对象。我的意思是一个人可以指向两个汽车对象,对吗?
-
同一个人对象? - 没有
-
好的。明白了,谢谢:)
标签: python django python-2.7 python-3.x django-models