我想在创建汽车模型实例时创建4个轮胎实例和1个引擎实例 这是我的模型代码
class car_form(forms.ModelForm):
class Meta:
model = Car
fields = (
'comapany',
'car_model',
'year'
)
def save(self, commit=True):
obj=car_form.save()
obj.company = self.cleaned_data['comapany']
obj.car_model = self.cleaned_data['car_model']
obj.year = self.cleaned_data['year']
if commit:
obj.save()
return obj
和汽车的表格
def car_create(request):
if request.method =='POST':
form = car_form(request.POST)
if form.is_valid():
form.save()
return redirect("/")
else :
return render(request, 'agency/car_form.html',
{'form': form})
else:
form = car_form()
args = {'form': form}
return render(request, 'agency/car_form.html', args)
这是我的观点
slideUp
我应该在代码中更改什么 我只是一个自学初学者,请原谅我的问题 提前谢谢
答案 0 :(得分:0)
您可以根据父实例创建实例,如:
...
new_car = form.save()
engine = Engine.objects.create(car=new_car)
for i in range(4):
tyre = Tyre.objects.create(car=new_car)
...