Skip to main content
 首页 » 编程设计

python之使用外键保存 Django orm 模型

2025年05月04日22虾米姐

我正在尝试找出保存我使用 django orm 获得的模型的最佳方法。我有一个模型/表,User。此外,我有一个名为 ContactInfo 的模型/表,我们将外键存储到 User 表中。

我知道常见的 django orm 做法是将 ContactInfo 模型的外键放入 User 模型中,但在这一点上,我们不想向已经单一的用户表添加任何内容,所以我们将外键键入 ContactInfo 模型。

我知道我可以将 User 模型存储在 ContactInfo 模型中,在 ContactInfo 上调用 save,它应该保存 User 模型,但是如果我与用户及其联系信息存在一对多关系怎么办?我宁愿在联系信息模型/对象的(1-多个)实例中没有用户表的多个实例。

如果我能解决任何问题,请告诉我。目前,我最好的想法是将 ContactInfo 列表的实例存储为 user.contact_info,并覆盖用户 user.save() 的保存方法检查 contact_info,如果存在,则将 user.id 插入每个模型并保存。不幸的是,我只是觉得这有点乱,但是作为 django 和 python 的新手,我不确定我的选择是什么。

非常感谢任何帮助,谢谢!

请您参考如下方法:

我不确定我是否正确理解了你的问题。 Django 对 1-N 关系提供了很好的支持。如果 ContactInfo 有一个外键 User,默认情况下,它是一个 1-N 映射。

ContactInfo   --------->   User 
             N          1 

So, there is only one User record in your database, looks like this

Table    User               Table ContactInfo 
--------------------------------------------- 
id     user_name              id     user_id 
 1       someone               1           1 
                               2           1 
                               3           1 

And you don't need to override save method. When you need to add a Contact,

contact = ContactInfo(user=target_user) 
# other stuff 
contact.save() 
#or  
target_user.contactinfo_set.create(...)#contactinfo_set is the related name of target_user 
#Django maintains the foreign key things. 

如果您使用上述方法插入新的 ContactInfo 记录,则无需迭代您的 contact_info 列表以将 user.id 插入数据库。