Django create/update multiple models in one rest request

I have a form in Vue which takes in data that is spread into multiple models when sent to django .

Rest JSON is

    data = {
  people:{
    name: "MyName",
    age: 34

  },
  classes:{
    name:"Valgris",
    tag:3492,
    comment:"gob gdjoisu is tsutsi"

  }
}

-THE MODELS FIELD IN DJANGO ARE

class Classes(models.Model):
    name = models.CharField(_ max_length=50) 
    age = models.IntegerField() 

class People(models.Model):
    name = models.CharField(_ max_length=50) 
    tag = models.IntegerField() 
    comment= models.TextField()

--- I tried tried using perform_create in my view, and also use create in serializer but I am unable to do it. request.data does not seem to like me popping out data and saving the result. It just doesn't work well.

Is there a way out. or do I have to send two request to create People and Classes model

1 answer

  • answered 2021-06-10 12:02 Shamsail

    I think you have to use two request for your purpose. As serializer of django-rest-framework requires your request.data as an argument,

    yourSerializer(yourModel, data=request.data)
    

    so it will not operate with the data of two models that you are sending from vue. Also, If you want to do these API calls with one another then you can call other API inside the first one API's response.

    axios
      .post("first/API/call/url", dataModel1, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
       })
      .then((response) => {
         console.log(response); 
         axios
           .post("second/API/call/url", dataModel2, {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            })
           .then((response) => {
               console.log(response); 
           })
           .catch((error) => {
               console.log(error);
         });
    
       })
       .catch((error) => {
           console.log(error);
       });
    

    Note: popping out data and changing it is fine for one model but for two model it's not fine.