2

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.

Craig Labenz
  • 2,489
  • 3
  • 22
  • 17
  • I believe in my post I answer your question. Here is: http://stackoverflow.com/questions/26608903/avoid-django-def-post-duplicating-on-save/26619058#26619058 – Ronaldo Bahia Oct 28 '14 at 21:49

1 Answers1

1

Why don't you just remove the through ManyToManyField from your ModelForm?

class MyForm(forms.ModelForm):
    class Meta:
        exclude = ('book',)
        model = Treatment
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 2
    So you have removed it and the model saves the first M2M field. How do you go about dealing with saving the 'through' M2M? – automagic Mar 07 '13 at 16:53