我已经阅读了Django中关于ManyToMany关系的所有内容,但到目前为止,我没有看到任何解决我的具体问题的问题,即Django处理的简单ManyToMany和ManyToMany-Through关系毫不费力地靠自己。
考虑这些模型:
class Treatment(models.Model):
...
book = models.ManyToManyField(Book, through='TreatmentLocation')
category = models.ManyToManyField(Category)
class Book(models.Model):
name = models.CharField(...)
class TreatmentLocation(models.Model):
treatment = models.ForeignKey(Treatment)
book = models.ForeignKey(Book)
page = models.CharField(...)
class Category(models.Model):
name = models.CharField(...)
我已经很好地获得了POST数组中的数据,但是查看视图却很棘手。
def save_treatment(request):
form = TreatmentForm(request.POST)
if form.is_valid():
treatment = form.save()
pages = request.POST.getlist('page')
books = request.POST.getlist('book')
counter = 0
for page in pages:
book_id = books.__getitem__(counter)
TreatmentLocation.objects.create(treatment_id=treatment.id, book_id=book_id, page=page)
counter = counter + 1
form.save_m2m()
else:
...
治疗保存成功,与TreatmentLocations一样,但是一旦我尝试调用save_m2m()来存储治疗类别外部参照,我就会收到Cannot set values on a ManyToManyField which specifies an intermediary model. Use TreatmentLocation Manager
错误。
有谁知道如何保存这两件事?我想避免诉诸原始SQL。
答案 0 :(得分:1)
为什么不从through
删除ManyToManyField
ModelForm
?
class MyForm(forms.ModelForm):
class Meta:
exclude = ('book',)
model = Treatment