Django Models:分配ForeignKey对象而不保存到数据库

时间:2014-04-29 18:43:42

标签: django django-models

我有以下模型

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()

1 个答案:

答案 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() 无效并会引发错误。)