如果我像这样使用 modelformset_factory 创建一个表单集:
IngredientFormSet = modelformset_factory(RecipeIngredients, form=RecipeIngredientsForm)
formset = IngredientFormSet(request.POST)
我的表格看起来像这样
class RecipeIngredientsForm(forms.ModelForm):
Ingredient = forms.CharField(max_length= 100)
class Meta:
model = RecipeIngredients
exclude = ('weightmetric','recipe')
我应该把我的自定义 .save() 方法放在哪里?我会把它放在RecipeIngredientsForm 下吗?
[一个潜在的解决方案]
在您看来,请执行以下操作:
if formset.is_valid():
for form in formset:
obj = form.save(commit=False) #obj = RecipeIngredient model object
try:
ingredient_in_db = Ingredient.objects.get(name = form.cleaned_data.get('ingredientform'))
except:
ingredient_in_db = None
if ingredient_in_db:
obj.ingredient = ingredient_in_db
else:
new_ingredient = Ingredient.objects.create(name = form.cleaned_data.get('ingredientform'))
obj.ingredient = new_ingredient
obj.recipe = recipeobj
obj.save()
顺便说一句,我认为这种方法还允许我执行自定义 .save(),因为我在表单集中获取每个表单并对其执行 form.save(commit= False)。不过,在我看来,这样做更容易,因为我需要访问配方对象。