使用Django Rest框架来序列化自定义数据类型并返回响应 [英] using Django Rest framework to serialize custom data types and return response
问题描述
Django Rest框架中的大部分教程都解释了如何使用Django模型和进行CRUD操作。这是一个 GET
请求用户模型返回JSON格式的用户对象的属性,如果我使用JSON序列化程序。
我正在设计我的Django应用程序来处理查询并返回响应。
例如,我提供一个REST API来获取以下查询的结果
给我的用户名和部门的工资比XXX / p>
这是我的Django模型:
class UserProfile(AbstractUser):
age = models.PositiveIntegerField(_(age))
salary = models.PositiveIntegerField(_(salary))
AUTH_USER_MODEL =profiles.UserProfile
User = get_user_model()
类部门(models.Model):
users = models.ForeignKey(用户)
dept_name = models.CharField(max_length = 30)
现在我有以下DTO(数据传输对象):
class CustomResponse(object):
def __init __(self,user_name,salary,dept_name):
self.user_name = user_name
self.salary = salary
self.dept_name = dept_name
在我的REST服务使用DRF实现,我想要fo
@api_view(['GET'])
def getNameandDept(salary):
users = User.objects.filter(salary__gt = salary)
toreturn = []
用户的用户:
response = CustomResponse(user.first_name,user.salary,user.dept_name)
to_return.append(response)
return响应(to_return)
我不知道是使用Django休息框架提供的工具来实现上述方法的正确方法。
我期待这样的回应
[{user_name:matt,salary:5000,dept_name:ENG},{user_name:smith,salary:4000,dept_name :HR} ....]
谢谢
编辑
我希望DRF为这种序列化提供开箱即用的工具。我一直在使用JAX-RS API(运动衫和RESTeasy)进行这个序列化。
您不需要REST框架。所有你需要的是定义一个 serializer
类,而不是你拥有的 CustomResponse
。
serializers.py
from django.core.serializers.json import Serializer
class UserSerializer(Serializer):
def get_dump_object(self,obj):
mapped_object = {
'user_name': obj.first_name,
'salary':obj.salary,
'dept_name':obj.dept_name
}
return mapped_object
然后在您的 views.py
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =工资)
serializer = UserSerializer()
返回HttpResponse(serializer.serialize(users),mimetype ='application / json')
不要忘记定义 urls.py
url(r'^ users /(?P< salary> \d +)$',views.getNameandDept,name ='getNameandDept'),
PS。您绝对可以使用DRF进行此操作。这是一个基本的 GET
调用(通过工资过滤对序列化程序没有影响),所以你需要做的就是定义一个 ModelSerializer
只有三个字段的子类
class UserSerializer(serializers.ModelSerializer):
class Meta :
model = User
fields =('first_name','salary','dept_name')
然后序列化输出(注意稍微不同的语法)
serializer = UserSerializer(users)
return响应(serializer.data)
Most of the tutorials on Django Rest Framework explains using the Django models and doing CRUD operations. That is a GET
request on user model returns the attributes of user object in JSON format if I use JSON serializer.
I am designing my Django application to process a query and return response. For example, I provide a REST API to get the results of the following query
"Get me the user first name and department whose salary than XXX"
Here are my Django models:
class UserProfile(AbstractUser):
age = models.PositiveIntegerField(_("age"))
salary=models.PositiveIntegerField(_("salary"))
AUTH_USER_MODEL = "profiles.UserProfile"
User = get_user_model()
class Department(models.Model):
users=models.ForeignKey(User)
dept_name = models.CharField(max_length=30)
Now I have the following DTO (Data transfer object):
class CustomResponse(object):
def __init__(self, user_name, salary, dept_name):
self.user_name = user_name
self.salary = salary
self.dept_name=dept_name
In my REST service implemented using DRF, I want the following
@api_view(['GET'])
def getNameandDept(salary):
users=User.objects.filter(salary__gt=salary)
toreturn=[]
for user in users:
response=CustomResponse(user.first_name,user.salary,user.dept_name)
to_return.append(response)
return Response(to_return)
I am not sure what is the right way to implement the above, with the tools that Django rest framework provide.
I am expecting the response something like this
[{user_name:"matt", salary:"5000", dept_name:"ENG"},{user_name:"smith",salary:"4000", dept_name:"HR"}....]
Thanks
EDIT
I was hoping DRF provides out of box tool for this kind of serialization. I have been using JAX-RS API (jersey and RESTeasy) that does this serialization.
You don't really need the REST Framework for this. All you need is to define a serializer
class instead of the CustomResponse
that you have.
in serializers.py
from django.core.serializers.json import Serializer
class UserSerializer(Serializer):
def get_dump_object(self, obj):
mapped_object = {
'user_name': obj.first_name,
'salary': obj.salary,
'dept_name': obj.dept_name
}
return mapped_object
then in your views.py
from myapp.serializers import UserSerializer
def getNameandDept(request, salary):
users = User.objects.filter(salary__gt=salary)
serializer = UserSerializer()
return HttpResponse(serializer.serialize(users), mimetype='application/json')
Don't forget to define the salary
argument in your urls.py
url(r'^users/(?P<salary>\d+)$', views.getNameandDept, name='getNameandDept'),
PS. You absolutely can do this with the DRF as well. It is a basic GET
call (the filtering by salary has no effect on the serializer), so all you need to do there is define a ModelSerializer
subclass with just the three fields
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('first_name', 'salary', 'dept_name')
and then serialize the output (note the slightly different syntax)
serializer = UserSerializer(users)
return Response(serializer.data)
这篇关于使用Django Rest框架来序列化自定义数据类型并返回响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!