我正在尝试提供一些自定义表单集处理。用户可以选择删除表单和添加表单。在同一个函数中,我试图删除关联的对象并添加新对象。这是我正在处理的代码示例:
def addCategories(movie, category_formset):
if category_formset.deleted_forms:
for form in category_formset._get_deleted_forms:
obj_to_remove = form.save(commit=False)
movie.categories.remove(obj_to_remove)
for form in category_formset:
if form.cleaned_data.get('name') is not None:
obj = Category.objects.get_or_create_category(form.cleaned_data.get('name'))
movie.categories.add(obj)
movie.save()
问题是我认为我没有正确使用 ._get_deleted_forms 。它声称 category_formset._get_deleted_forms 是不可迭代的。而且我不确定这是否会起作用——因为它可能只是在第二个 for 循环中将已删除的对象添加回模型。有任何想法吗?
一种似乎不是很有效的解决方法:
def addCategories(recipe, category_formset):
if category_formset.deleted_forms:
for form in category_formset:
if form in category_formset.deleted_forms:
obj_to_remove = form.save(commit=False)
recipe.categories.remove(obj_to_remove)
else:
if form.cleaned_data.get('name') is not None:
obj = Category.objects.get_or_create_category(form.cleaned_data.get('name'))
recipe.categories.add(obj)
else:
for form in category_formset:
if form.cleaned_data.get('name') is not None:
obj = Category.objects.get_or_create_category(form.cleaned_data.get('name'))
recipe.categories.add(obj)
recipe.save()