Skip to main content
 首页 » 编程设计

python之在 Django 中使用带有外键的模型的正确方法

2025年05月04日35exmyth

我是 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:虽然我目前使用的是第一个,但它运行良好。

请您参考如下方法:

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

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