Skip to main content
 首页 » 编程设计

python之update_or_create 在外键的两个实例上覆盖字段对象

2024年12月31日9me-sa

大家好,我被这个问题困住了。 我知道 update_or_create 应该更新已经存在的字段 但它正在覆盖我正在创建或更新的数据字段。 示例:

class Branch(models.Model): 
    name = models.CharField() 
    ... 
class Office(models.Model): 
    name = models.CharField() 
    branch = models.ForeignKey(Branch) 

假设在分支内我有分支 A,分支 B 在分支 A 中我有一些对象,我想使用这些对象为分支 B 创建对象或更新它(如果它已经存在)。如果不覆盖分支 A 和分支 B 上的字段,我该怎么做。

请您参考如下方法:

我想出了解决这个问题的方法 使用 get_or_create 而不是 update_or_create 然后在分支 Foreignkey 和 name

中添加一个元类 unique_together