Django saving json value to database/model

前端 未结 5 742
清歌不尽
清歌不尽 2020-12-28 19:30

Im new to django and im trying to save json to database. The problem is that im able to get data the data in my views but not sure how to save it in

5条回答
  •  半阙折子戏
    2020-12-28 20:09

    Assuming a model of:

    class User(models.Model):
      name = models.CharField()
      phone_number = models.CharField()
    

    Sending json of {"name":"Test User", "phone_number":"123-456-7890"}

    In the view you could do the following to save it to the database.

    def SaveUser(request):
      body_unicode = request.body.decode('utf-8')
      body = json.loads(body_unicode)
      u = User(**body)
      u.save()
      return JsonResponse({"result": "OK"})
    

提交回复
热议问题