我有以下模型
class ModelA(models.Model):
a = models.CharField()
b = models.ForeignKey(ModelB)
class ModelB(models.Model):
c = models.CharField()
是否可以创建ModelB
的实例而不保存它,分配给ModelA
?
类似下面的内容
obj_b = ModelB(c='1')
obj_b.save(commit=False)
obj_a = ModelA(a='2', b=obj_b)
obj_a.save(commit=False)
# change obj_b attributes in between
# change obj_a attributes in between
obj_b.save()
obj_a.save()
答案 0 :(得分:0)
简短的回答是不是,因为ORM似乎没有发现obj_b
已被保存,但这应该不是问题,因为您需要做的就是分配{{ <}> 在保存obj_a.b = obj_b
之后。这应该有效:
obj_b
(注意,obj_b = ModelB(c='1')
obj_a = ModelA(a='2')
# change obj_b attributes in between
# change obj_a attributes in between
obj_b.save()
obj_a.b = obj_b
obj_a.save()
无效并会引发错误。)