Search code examples
pythondjangomodeldjango-serializermanytomanyfield

How to add middle IDs in third table with ManyToManyField in Django when using Serialaizer?


I have tables like this:

class Education(models.Model):
    title = models.CharField(default=None, max_length=100)
    content = models.TextField(default=None)
    price = models.ManyToManyField(Price)

class Price(models.Model):
    cost = models.CharField(default=None, max_length=20)

And from client get a request and try to save it in three tables, I have no problem with two tables Education and Price but because I'm using serializer i don't know how to update third table(middle).

def post(self, request):
    cost = request.POST.get('cost')
    price = Price.objects.create(cost=cost)

    education_serializer = EducationSerializer(data=request.data)
    if education_serializer.is_valid():
        education_serializer.save()

Good, here i have updated two tables, In the following i don't know how update third table. If i didn't use serializer i have could write it like this:

education.price.add(price)

Solution

  • The call of education_serializer.save returns an instance of Education, so you can write:

    def post(self, request):
        cost = request.POST.get('cost')
        price = Price.objects.create(cost=cost)
    
        education_serializer = EducationSerializer(data=request.data)
        if education_serializer.is_valid():
            education = education_serializer.save()
            education.price.add(price)