在Django中使用带外键的Models的正确方法

时间:2014-07-01 17:19:56

标签: python django python-2.7 python-3.x django-models

我是Django的新手,我对数据库知之甚少。

让我解释一下我的问题。 例如,我有两个模型 - 人和车(一个人可以有多辆车。)

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:虽然第一个我正在使用它并且它的工作完美。

1 个答案:

答案 0 :(得分:1)

假设一辆车只能拥有一个车主。 然后,我会这样写:

class Car(models.Model):
  owner = models.ForeignKey(Person, related_name='cars")

class Person(models.Model):
  # ... fields unrelated to cars