I read everything I can find in ManyToMany relationships in Django, but so far I have not seen anything that solves my specific problem with the ManyToMany-Through relationship along with the simple ManyToMany that Django processes so easily 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 have data coming in to a POST array, but stopping browsing seems complicated.
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:
...
Processing is successfully saved, as well as in the processing area, but as soon as I try to call save_m2m () to save links like "Treatment category", I get an error Cannot set values on a ManyToManyField which specifies an intermediary model. Use TreatmentLocation Manager.
Does anyone know how to save both of these things? I would like to avoid using raw SQL.