Django序列化程序与rest_framework序列化程序 [英] Django serializers vs rest_framework serializers

查看:78
本文介绍了Django序列化程序与rest_framework序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django序列化器 rest_framework序列化器有什么区别?
我制作了一个Webapp,我希望API成为该项目创建的主应用程序的一部分。没有为API功能创建单独的应用程序。我需要为Django视图和模型使用哪个序列化程序,并且同时适用于该API?

 来自django.core导入序列化程序

https://docs.djangoproject.com/ zh_cn / 3.0 / topics / serialization /

 来自rest_framework导入序列化程序

https://www.django-rest-framework.org/api-guide/serializers/

解决方案

tl; dr


如果您只想创建很少个非常小的API端点,而不要使用DRF,您最好手动构建词典。 Django核心序列化程序不适合外部使用者使用。




您可以在项目中使用相同的主应用程序,并使其与DRF一起使用。平行。只需添加带有定义的 serializers.py 文件,在同一 views.py 文件中添加DRF逻辑,然后执行路由。您可以使用基于函数的视图


差异的详细说明


假设您有以下模型

  class Employee(models.Model):
Identification_number = models.CharField(max_length = 12)
first_name = models.CharField(max_length = 50)
last_name = models.CharField (max_length = 50)

您要创建端点 / employees / 返回所有具有JSON表示形式的此类对象

  {
first_name: Jon,
last_name: Skeet
}




使用Django序列化程序


< pre class = lang-py prettyprint-override> 来自django.core导入序列化器
,来自django.http导入HttpResponse

class EmployeeView(View):
def get(self,request):
员工= Employee.objects.all()
序列化= serializers.serialize(
'json',
员工,
fields =('first_name','last_name'),

返回HttpResponse(序列化)

,您得到的结果将是以下格式的字典列表:

  {
fields :{
first_name : Jon,
last_name; : Skeet
},
model : employees.Employee,
pk; :12
}

但这不是我们想要的。 Django核心序列化程序旨在将模型序列化为内容的表示在数据库中。通过 dumpdata这一事实可以明确地表明这一点。 命令使用它

  python manage.py dumpdata employee.Employee | json_pp 


  [
{
fields :{
identification_number : 20201293,
first_name : Jon,
last_name; :飞碟
},
model : employees.Employee,
pk; :12
}
]

现在,您当然可以对代码做一些事情了获得所需的表示形式,但该模块并非供外部使用者使用API​​视图




< h2>使用Django REST框架

在这里,我们可以创建独立于Model的序列化器类。这一点很重要,因为该对象的外部表示与内部表示是分开的。

  class EmployeeSerializer(serializers。 ModelSerializer):

类元:
模型=员工
字段=(
'first_name',
'last_name',

,并且尝试仅使用DRF的最基本的序列化/反序列化功能,我们会得到

  from rest_framework.renderers从django中导入JSONRenderer 
.http import HttpResponse

class EmployeeView(View):
def get(self,request):
员工= Employee.objects.all()
序列化= EmployeeSerializer(员工,很多=真实)
json_representation = JSONRenderer()。render (serialized.data)
返回HttpResponse(json_representation)

并得到表示形式w


现在,您当然通常不像上一个示例那样使用DRF,而是

 从rest_framework导入视图集

class EmployeeViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer

它可以处理所有样板,因此非常方便,与Django核心序列化程序相比,这是真的对外部消费者有用。


What is the difference between Django serializers vs rest_framework serializers? I making a webapp, where I want the API to be part of the primary app created by the project. Not creating a separate App for the API functionality. Which serializer do I need to use for Django views and models, and at the same time will work for the API?

from django.core import serializers

https://docs.djangoproject.com/en/3.0/topics/serialization/

from rest_framework import serializers

https://www.django-rest-framework.org/api-guide/serializers/

解决方案

tl;dr

If you want to create just a few very small API endpoints and don't want to use DRF, you're better off manually building the dictionaries. Django core serializers are not meant for external consumers.


You can use the same primary app in your project and make it work with DRF in parallel. Just add a serializers.py file with the definitions, add the DRF logic in the same views.py file and do the routing. You could use function based views.

Detailed explanation of differences

Let's say you have the following model

class Employee(models.Model):
  identification_number = models.CharField(max_length=12)
  first_name = models.CharField(max_length=50)
  last_name = models.CharField(max_length=50)

And you want to create an endpoint /employees/ that returns all such objects with JSON representation

{
  "first_name": "Jon",
  "last_name": "Skeet"
}


With Django serializers

from django.core import serializers
from django.http import HttpResponse

class EmployeeView(View):
    def get(self, request):
        employees = Employee.objects.all()
        serialized = serializers.serialize(
          'json',
          employees,
          fields=('first_name', 'last_name'),
        )
        return HttpResponse(serialized)

and the result you get would be a list of dictionaries of the form

{
      "fields" : {
         "first_name" : "Jon",
         "last_name" : "Skeet"
      },
      "model" : "employees.Employee",
      "pk" : 12
}

But this isn't what we're looking for. Django core serializers are meant to serialize models as representations of what's in the database. This is made explicit by the fact that the dumpdata command uses it.

python manage.py dumpdata employees.Employee | json_pp

[
  {
      "fields" : {
         "identification_number" : "20201293",
         "first_name" : "Jon",
         "last_name" : "Skeet"
      },
      "model" : "employees.Employee",
      "pk" : 12
  }
]

Now, of course you could do some things to your code to get the representation you want, but this module is not meant to be used for API views to be consumed by a external consumer.


With Django REST framework

Here we can create serializer classes that are independent of the Model. This is important since the external representation of the object is kept separate from the internal one.

class EmployeeSerializer(serializers.ModelSerializer):

  class Meta:
    model = Employee
    fields = (
      'first_name',
      'last_name',
    )

and, trying to use only the most basic serialization-deserialization features of DRF, we would get

from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse

class EmployeeView(View):
    def get(self, request):
        employees = Employee.objects.all()
        serialized = EmployeeSerializer(employees, many=True)
        json_representation = JSONRenderer().render(serialized.data)
        return HttpResponse(json_representation)

and result in the representation we were looking for.

Now, of course you usually don't use DRF as in the last example, but instead

from rest_framework import viewsets

class EmployeeViewSet(viewsets.ReadOnlyModelViewSet):
  queryset = Employee.objects.all()
  serializer_class = EmployeeSerializer

It takes care of all the boilerplate so it's really convenient and, in contrast with the Django core serializers, this is really meant for external consumers.

这篇关于Django序列化程序与rest_framework序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆