下面是簡化的示例的什麼,我想實現:手動保存的ModelForm相對外鍵
class Product(models.Model):
# some data, does not really matter
class ProductAttributeValue(models.Model):
product = models.ForeignKey('Product')
value=models.CharField(_("value"),max_length=100)
....
class ProductForm(forms.ModelForm):
def __init__(self,*args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
#Here, I am dynamically constructing and injecting attributes.
#my products have dynamic attributes
# the filled-in values of these attributes need to be saved as ProductAttributeValue instances
#...
def save(commit):
m = super(ProductForm, self).save(commit=False)
#looping thru my custom attributes and constructing instances
#to simplify I will just put one example
attr_val=ProductAttributeValue(product=m)
attr_val.value=self.clean_data['myval']
m.productattributevalue_set.add(attr_val)
if commit:
m.save()
# also doing m2m_save if exists
return m
所以我期待這個失敗的product_id =無錯誤。我也嘗試瞭解django的InlineForm(在管理端)是如何工作的,但似乎他們首先保存了主產品,然後保存了ProductAttributeValue,並且如果說ProductAttributeValue保存失敗了,那麼他們很好。 對於我的情況,這是不可接受的,即我應該保存所有表格(產品和價值)或失敗。我可以肯定地從一開始就用commit = True保存,但正如我所說的,我不希望產品被保存並且不值的情況。
任何幫助表示讚賞。
當然,你不能一個未保存的實例添加到另一個未保存的實例。調用'save()'然後賦值屬性有什麼問題?你是否期望它以某種方式失敗?如果你這樣做,那麼下面有關於交易的答案。我只是好奇你爲什麼在這裏期待失敗..你應該事先做驗證,以確保它不會在數據庫級別失敗。 – 2012-02-03 03:05:15