how to bind HTTP POST data to python object in Django Rest Framework?

和自甴很熟 提交于 2020-01-05 08:24:06

问题


I will give an example to better explain my question

my request:

POST

http://localhost:8080/users/

request body: (This gets posted)

{"name":"Matt", 
 "salary":10000,
 "blog_url":"www.myblog.com",
 "dept_name":"ENG"
}

class CustomRequest(object):
    def __init__(self,name,salary,blog_url,dept_name):
       self.name=name
       self.salary=10000
       self.blog_url=blog_url
       self.dept_name=dept_name

models.py

class myUser(models.Model):
     //fields -- username, salary

class myUserProfile(models.Model):
      User=models.OneToOneField(user)
      blog_url=models.URLfield()
      dept_name=models.ForeignKey(Department)



@apiview(['POST'])
def createUser(customrequest):
      myuser=user(customrequest.name, customrequest.salary)
      myuser.save()

      myuser.userprofile.blog_url(customrequest.blog_url)
      myuser.userprofile.dept_name(customrequest.dept_name)
      myuser.save()

I have been most of REST services using Java JAX-RS API. In this framework, POST request body is automatically deserialized to the object that the method takes in( in the above example, it is customrequest). A developer can define an object with attributes that he is looking for in the POST request and then perform the business logic.

Now that we are thinking of migrating to Django, I am wondering if Django Rest Framework provides this kind of behavior out of box. If so, how would I do that? Please note, in the JAX-RS world, there is no need for a developer to write a serializer. All that is needed is the transfer object where the incoming JSON gets deserailzed into.

I assume in Django, both a serializer and a transfer object is needed to achieve the same purpose.


回答1:


In DRF, you have two options:

  • either you use ModelSerializer and you get the model instance automatically
  • or you use Serializer and you get the validated_data and do whatever you like with it

The serializer is the same as what you call transfer object, in the sense that both define the data structure and that both will hold the deserialized values.

For models, it is required for persistence, but that is also required in JAX-RS, unless you use the same classes as ORM entities(which is a bad design). So in JAX-RS you will have, for example, CustomRequest and JPA CustomRequestEntity



来源:https://stackoverflow.com/questions/28331554/how-to-bind-http-post-data-to-python-object-in-django-rest-framework

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