我想将数据保存到中间模型并在模型中进行一些计算(通过覆盖模型保存)。我遇到的问题是formset无法保存到中间模型。
只有在存在M2M关系时才会创建中间模型(据我所知)。
我有4个这样的模型:
Category(models.Model):
name = models.CharField(..)
Tax(models.Model):
name = models.CharField(..)
rate = models.DecimalField(..)
CategoryItem(models.Model):
category = models.ForeignKey(Category)
taxes = models.ManyToManyField(Tax, through='CategoryItemTax', through_fields=('item', 'tax'))
quantity = models.DecimalField(..)
price = models.DecimalField(..)
# intermediary model below
CategoryItemTax(models.Model):
category = models.ForeignKey(Category)
tax = models.ForeignKey(Tax)
item = models.ForeignKey(CategoryItem)
rate = models.DecimalField(..) #derived from tax object in the model
total_tax = models.DecimalField(..) #calculated in model save
我有一个带有CategoryItem formset的Category模型表单。我的views.py如下:
class FormsetMixin(object):
object = None
def post(self, request, *args, **kwargs):
if getattr(self, 'is_update_view', False):
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
formset_class = self.get_formset_class()
formset = self.get_formset(formset_class)
if form.is_valid() and formset.is_valid():
return self.form_valid(form, formset)
else:
return self.form_invalid(form, formset)
# THE SAVE METHOD
def form_valid(self, form, formset):
self.object = form.save()
formset.instance = self.object
instances = formset.save(commit=False)
for i in instances:
CategoryItemTax.objects.create(category=self.object, item=i, tax=i)
CategoryItemTax.save()
class CategoryCreateView(FormsetMixin, CreateView):
template_name='..'
model = Category
form_class = CategoryForm
formset_class = CategoryItemFormSet
Forms.py如下
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
class CategoryItemForm(forms.ModelForm)
class Meta:
model = CategoryItem
CategoryItemFormSet = inlineformset_factory(Category, CategoryItem, form=CategoryItemForm, extra=1)
不幸的是我收到以下错误:
Cannot set values on a ManyToManyField which specifies an intermediary model.
Use category.CategoryItemTax's Manager instead
答案 0 :(得分:0)
像这样编辑您的视图,
def form_valid(self, form, formset):
self.object = form.save()
formset.instance = self.object
instances = formset.save(commit=False)
for each in instances:
each.category = self.object
each.save()
item = CategoryItemTax.objects.create(category=self.object, item=each)
item.save()
必须首先保存多对多的相关对象才能与另一个实例关联。