如何有条件地使用django多表继承保存表单 [英] how to conditionally save a form using django multi table inheritance
问题描述
我有以下形式:
class PlaceForm(forms.ModelForm):
class 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()
在我看来,我想有条件地保存一个地方或一个餐厅取决于传入的网址。
In my view I want to conditionally save either a Place or a Restaurant depending on the incoming url.
我尝试了以下内容:
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,列'customer_id'不能为空)
This creates a place from the form and then tries to create a restaurant, but fails with following: (1048, "Column 'customer_id' cannot be null")
这是告诉我新的一个地方试图插入餐厅排。
This is telling me that a new row for a new place is trying to be inserted and then the restaurant row.
我看到一个几个不同的选项:
I see a few different options:
- 将该地方转换为餐厅,并将其另存为转换对象。
- 有条件地将表单的模型类型更改为Place或Restaurant
如何有条件地保存不同的父项和子对象?
How can I accomplish saving the different parent and child objects conditionally?
推荐答案
与 Django模型继承:crea现在的实例(downcast)的子实例?,它建议如何使用现有的基类对象添加对象。
It is related to Django model inheritance: create sub-instance of existing instance (downcast)? which suggests how to add object with existing base class object.
你可能想看看我的问题:派生模型文件夹不可用
You may want to look at my question: Derived model filefield not available
简单来说,您要做的是
restaurant = Restaurant(place_ptr_id=place.id)
restaurant.__dict__.update(place.__dict__)
restaurant.save()
这篇关于如何有条件地使用django多表继承保存表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!