我正在尝试提供一些自定义的formset处理。用户可以选择删除表单并添加表单。在同一个函数中我试图删除关联的对象并添加新对象。这是我正在处理的代码示例:
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()