我想將數據保存到中間模型並在模型中進行一些計算(通過重寫模型保存)。我遇到的問題是formset無法保存到中間模型。Django formset with manytomany through intermediate model
中介模型僅在存在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表單集一類模型的形式。我的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
你可以顯示錶單嗎? – zaidfazil
我已經添加了forms.py代碼。 – Hdman