Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to save a django model with a manyToMany Through relationship, AND regular manyToMany relationships
    text
    copied!<p>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.</p> <p>Consider these models:</p> <pre><code>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(...) </code></pre> <p>I've got the data coming in on the POST array nicely, but finagling the View is proving tricky.</p> <pre><code>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: ... </code></pre> <p>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 <code>Cannot set values on a ManyToManyField which specifies an intermediary model. Use TreatmentLocation Manager</code> error.</p> <p>Does anyone know how to save both of these things? I'd like to avoid resorting to raw SQL.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload