问题
I've read everything I can find on ManyToMany relationships in Django, but so far I'm not seeing anything that solves my specific problem of having a ManyToMany-Through relationship alongside a simple ManyToMany that Django handles so effortlessly on its own.
Consider these models:
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(...)
I've got the data coming in on the POST array nicely, but finagling the View is proving tricky.
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:
...
The Treatment saves successfully, as do the TreatmentLocations, but once I try to call save_m2m() to store the Treatment-Category xrefs, I get the Cannot set values on a ManyToManyField which specifies an intermediary model. Use TreatmentLocation Manager
error.
Does anyone know how to save both of these things? I'd like to avoid resorting to raw SQL.
回答1:
Why don't you just remove the through
ManyToManyField
from your ModelForm
?
class MyForm(forms.ModelForm):
class Meta:
exclude = ('book',)
model = Treatment
来源:https://stackoverflow.com/questions/9146208/how-to-save-a-django-model-with-a-manytomany-through-relationship-and-regular-m