给定另一个Model字段时如何保存OneToOne模型?

时间:2014-02-19 08:18:00

标签: django django-models

使用这个例子:

class ModelA(Model):
     name = CharField(max_length=100, unique=True)

class ModelB(Model):
     modela = OneToOneField(ModelA)
     otherfield = ManyToManyField(...)
     ...

然后,在给定ModelA名称时如何保存ModelB表单?

我在观点中尝试过类似的内容:

def modelbSave(request, modelA_name):
        modelA = ModelA.objects.get(name=modelA_name)
        modelB = ModelB.objects.get(modela=modelA)

        if request.method == "POST":
             # Edit existing modelB or save a new one
             modelB_form = ModelBForm(request.POST, instance=modelB)

             if modelB_form.is_valid():
                   modelB = modelB_form.save(commit=False)
                   modelB.modela = modelA  # save modelA relationship
                   modelB.save()
                   modelB_form.save_m2m()   # save other m2m relationships in modelB

        else:
             ....

但是我在这一行得到了错误:

modelB = ModelB.objects.get(modela=modelA)

错误说:

Exception Value: modelB matching query does not exist.

0 个答案:

没有答案