【问题标题】:how to conditionally save a form using django multi table inheritance如何使用 django 多表继承有条​​件地保存表单
【发布时间】: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")

这告诉我正在尝试插入新地方的新行,然后是餐厅行。

我看到了几个不同的选项:

  1. 将 Place 转换为餐厅,并将附加内容保存到转换后的对象中。
  2. 有条件地将表单的模型类型更改为 Place 或 Restaurant

如何有条件地保存不同的父子对象?

【问题讨论】:

标签: django inheritance django-models django-forms multi-table-inheritance


【解决方案1】:

它与Django model inheritance: create sub-instance of existing instance (downcast)? 相关,它建议如何使用现有的基类对象添加对象。

你可能想看看我的问题:Derived model filefield not available


简而言之,你要做的是

restaurant = Restaurant(place_ptr_id=place.id)
restaurant.__dict__.update(place.__dict__)
restaurant.save()

【讨论】:

    【解决方案2】:

    您可以添加null=Trueblank=True

    型号:

    class Place(models.Model):
        customer = models.ForeignKey(Customer, null=True, blank=True)
        name = models.CharField(max_length=50)
        address = models.CharField(max_length=80)
    

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 2012-03-08
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多