为什么我不能在ModelForm的save()函数中设置OneToOneField?

时间:2016-04-20 15:50:15

标签: django django-models django-forms django-admin

假设我们有两个模型:

model.py

class Engine(models.Model):
    name = models.CharField(max_length=25)

class Car(models.Model):
    name = models.CharField(max_length=25)
    engine = models.OneToOneField(Engine)

engine_admin.py

class EngineAdmin(admin.ModelAdmin):
     def get_changelist_form(self, request, **kwargs):
         return EngineChangeListForm

form.py

class EngineChangeListForm(forms.ModelForm):
    class Meta:
        model = Engine
        fields = []
    # this work!
    def save(self, *args, **kwargs):
        car_obj = Car.objects.create(engine = self.instance)
        return super(EngineChangeListForm, self).save(*args, **kwargs)

如果我将save()改为下面,它会创建一个新的汽车对象,但最后,引擎对象的car字段将为空。

我不明白为什么下面的代码不起作用。

# this won't work!
def save(self, *args, **kwargs):
     car_obj = Car.objects.create(engine = self.instance)
     self.instance.car = car_obj
     return super(EngineChangeListForm, self).save(*args, **kwargs)

1 个答案:

答案 0 :(得分:2)

在创建汽车之前,您需要首先致电def save(self, *args, **kwargs): instance = super(EngineChangeListForm, self).save(*args, **kwargs) car_obj = Car.objects.create(engine=instance) return instance 以保存引擎。

group by