【问题标题】:Django create/update multiple models in one rest requestDjango 在一个休息请求中创建/更新多个模型
【发布时间】:2021-06-10 10:52:20
【问题描述】:

我在 Vue 中有一个表单,它接收发送到 django 时分散到多个模型中的数据。

其余的 JSON 是

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

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

  }
}

-DJANGO 的模型领域是

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()

--- 我尝试在我的视图中使用 perform_create,并在序列化程序中使用 create,但我无法做到。 request.data 似乎不喜欢我弹出数据并保存结果。就是效果不好。

有没有出路。还是我必须向 create People 和 Classes 模型发送两个请求

【问题讨论】:

    标签: django vue.js django-rest-framework


    【解决方案1】:

    我认为你必须使用两个请求来达到你的目的。 由于django-rest-frameworkserializer 需要您的request.data 作为参数,

    yourSerializer(yourModel, data=request.data)
    

    因此它不会对您从vue 发送的两个模型的数据进行操作。 此外,如果您想彼此进行这些API 调用,那么您可以在第一个API 的响应中调用其他API

    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);
       });
    

    注意:弹出数据并更改数据对于一个模型是可以的,但对于两个模型则不行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-12
      • 2018-11-26
      • 1970-01-01
      • 2017-09-12
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多