简体   繁体   English

如何使用Django REST序列化器?

[英]How to use Django REST Serializers?

So, after reading the Django REST Framework document, and a bunch of tutorials, I am still having trouble understanding how to use the Django serializers to convert incoming POST (JSON) data into a Python object (sorry, I'm new). 因此,在阅读了Django REST Framework文档和大量教程之后,我仍然很难理解如何使用Django序列化器将传入的POST(JSON)数据转换为Python对象(对不起,我是新手)。

Given that I am posting a JSON string to, say, api/foo/bar, how do I write its serializer? 假设我要向api / foo / bar发布JSON字符串,如何编写其序列化器?

Example JSON: JSON示例:

{ 'name': 'Mr. Foo', address:'Bar Street' }

My controller, Foo contains a bar method as follows: 我的控制器Foo包含一个bar方法,如下所示:

@detail_route(
    methods=['post']
)
def bar(self, request, uuid=None):
    serializer = MySampleSerializer(data=request.DATA)

    something.clone(serializer.object)
    return Response(status=status.HTTP_201_CREATED)

Can somebody explain to me what should my serializer look like? 有人可以向我解释我的串行器应该是什么样吗? And how do I access the serialized data from the serializer? 以及如何从序列化器访问序列化的数据?

As you do not want to use a model, you have to create the serializer from scratch. 由于您不想使用模型,因此必须从头开始创建序列化程序。 Something like this should maybe work: 这样的事情也许应该起作用:

class MySerializer(serializers.Serializer):
    name = serializers.CharField(max_length = 100)
    adress = serializers.CharField(max_length = 100)

And then you could use it in a request like this: 然后您可以在这样的请求中使用它:

def bar(self, request, uuid=None):
    data = JSONParser().parse(request)
    serializer = MySerializer(data = data)
    return Response(status=status.HTTP_201_CREATED)

Note however, as you have not created an Django model, you will not be able to save the serialized data (and thus nothing will be saved in the database) 但是请注意,由于您尚未创建Django模型,因此您将无法保存序列化数据(因此,数据库中将不会保存任何内容)

Basically, you pass in the JSON data to the serializer, and then access the data field which will return an ordered dictionary. 基本上,您将JSON数据传递给序列化器,然后访问数据字段,这将返回有序字典。

def bar(self, request, uuid=None):
    serializer = MySampleSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        my_object = serializer.data # Grab the dict of values

To define a serializer: 定义序列化器:

class MySampleSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=30)
    address = serializers.CharField(max_length=30)

You do not have to use the ModelSerializer: 您不必使用ModelSerializer:

from rest_framework import serializers

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

and access: 和访问:

serializer = CommentSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data

by the way, all the above is from the DRF website 顺便说一句,以上所有内容均来自DRF 网站

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM