How to save a django model with a manyToMany Throu

2019-07-30 15:31发布

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条回答
虎瘦雄心在
2楼-- · 2019-07-30 16:11

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

class MyForm(forms.ModelForm):
    class Meta:
        exclude = ('book',)
        model = Treatment
查看更多
登录 后发表回答