【发布时间】:2013-10-03 04:24:41
【问题描述】:
我有以下表格:
类 PlaceForm(forms.ModelForm):
class Meta:
model = Place
我有以下型号:
class Place(models.Model):
customer = models.ForeignKey(Customer)
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
在我看来,我想根据传入的 url 有条件地保存 Place 或 Restaurant。
我尝试了以下方法:
if form.is_valid():
place = form.save(commit=False)
place.customer = customer
place.save()
if url_name == 'restaurant':
restaurant = Restaurant(place_ptr_id=place.id)
restaurant.save()
这会从表单创建一个地方,然后尝试创建一家餐厅,但失败并显示以下内容:(1048, "Column 'customer_id' cannot be null")
这告诉我正在尝试插入新地方的新行,然后是餐厅行。
我看到了几个不同的选项:
- 将 Place 转换为餐厅,并将附加内容保存到转换后的对象中。
- 有条件地将表单的模型类型更改为 Place 或 Restaurant
如何有条件地保存不同的父子对象?
【问题讨论】:
-
这与扩展 django auth 用户有关。我觉得这有点不同。
标签: django inheritance django-models django-forms multi-table-inheritance