如何将HTTP POST数据绑定到Django Rest Framework中的python对象? [英] how to bind HTTP POST data to python object in Django Rest Framework?
问题描述
我将举个例子来更好地解释我的问题
I will give an example to better explain my question
我的请求:
POST
http:// localhost:8080 / users /
请求正文:(发布)
{"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
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()
我使用Java JAX-RS API大部分REST服务。在此框架中,
POST请求体自动反序列化为方法所接收的对象(在上例中,它是customrequest)。开发人员可以使用POST请求中寻找的属性定义一个对象,然后执行业务逻辑。
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.
现在我们正在考虑迁移到Django,我想知道Django Rest Framework是否提供了这种类型的行为。如果是这样,我该怎么办?
请注意,在JAX-RS世界中,开发人员无需编写序列化程序。所有需要的是传入的JSON被分配到的传输对象。
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.
我假设在Django中,需要一个串行器和一个传输对象来达到相同的目的
I assume in Django, both a serializer and a transfer object is needed to achieve the same purpose.
推荐答案
在DRF中有两个选项:
In DRF, you have two options:
- 您可以使用ModelSerializer,并自动获取模型实例
- ,或者使用Serializer,并获得validated_data并执行任何您喜欢的操作
序列化程序与您所说的传输对象
相同,就是在定义数据的意义上结构,并且两者都将保存反序列化的值。
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.
对于模型,它是持久性所必需的,但JAX-RS中也是必需的,除非您使用相同的类作为ORM实体(这是一个坏的设计)。所以在JAX-RS中你会有,例如,CustomRequest和JPA CustomRequestEntity
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
这篇关于如何将HTTP POST数据绑定到Django Rest Framework中的python对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!