How to save a django model with a manyToMany Through relationship, AND regular manyToMany relationships

匆匆过客 提交于 2020-01-05 03:43:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!