假设我们有两个模型:
class Engine(models.Model):
name = models.CharField(max_length=25)
class Car(models.Model):
name = models.CharField(max_length=25)
engine = models.OneToOneField(Engine)
class EngineAdmin(admin.ModelAdmin):
def get_changelist_form(self, request, **kwargs):
return EngineChangeListForm
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)
答案 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