AI智能
改变未来

Django Rest Framework的基础组件使用方法之序列化:一个简单的案例

这个案例来自于官网django-rest-framework.org

一,搭建开发环境

1,创建django项目tutorial

django-admin.py startproject tutorial

2,创建应用snippet

python manage.py startapp snippet

3,安装DRF

pip install djangorestframeworkpip install pygments  # 用于代码高亮

4,配置settings.py

INSTALLED_APPS = (...\'rest_framework\',\'snippet.apps.SnippetConfig\',)

完成后项目结构如下:

二,模型及其序列化

1,创建模型Snippet

在snippet/models.py中创建模型Snippet

from django.db import modelsfrom pygments.lexers import get_all_lexersfrom pygments.styles import get_all_styles# 提取出了 pygments 支持的所有语言的词法分析程序LEXERS = [item for item in get_all_lexers() if item[1]]# 提取出了 pygments 支持的所有语言列表LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])# 提取出了 pygments 支持的所有格式化风格列表STYLE_CHOICES = sorted((item, item) for item in get_all_styles())# Create your models here.class Snippet(models.Model):created = models.DateTimeField(auto_now_add=True)title = models.CharField(max_length=100, blank=True, default=\'\')code = models.TextField()linenos = models.BooleanField(default=False)  # 是否显示行号language = models.CharField(choices=LANGUAGE_CHOICES, default=\'python\', max_length=100)style = models.CharField(choices=STYLE_CHOICES, default=\'friendly\', max_length=100)class Meta:ordering = (\'created\',)

2,数据迁移

python manage.py makemigrations snippetspython manage.py migrate

产生如下数据表:

3,使用Serializer创建模型的序列化类

在 snippet 的目录下创建一个名为 serializers.py 文件:

from rest_framework import serializersfrom snippet.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICESclass SnippetSerializer(serializers.Serializer):id = serializers.IntegerField(read_only=True)title = serializers.CharField(required=False, allow_blank=True, max_length=100)code = serializers.CharField(style={\'base_template\': \'textarea.html\'})linenos = serializers.BooleanField(required=False)language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default=\'python\')style = serializers.ChoiceField(choices=STYLE_CHOICES, default=\'friendly\')def create(self, validated_data):\"\"\"给定验证过的数据创建并返回一个新的 Snippet 实例。\"\"\"return Snippet.objects.create(**validated_data)def update(self, instance, validated_data):\"\"\"根据已验证的数据更新并返回已存在的 Snippet 实例。\"\"\"instance.title = validated_data.get(\'title\', instance.title)instance.code = validated_data.get(\'code\', instance.code)instance.linenos = validated_data.get(\'linenos\', instance.linenos)instance.language = validated_data.get(\'language\', instance.language)instance.style = validated_data.get(\'style\', instance.style)instance.save()return instance
  • 序列化器类的第一部分定义了获得序列化/反序列化的字段。
  • create() 和 update() 方法定义了在调用 serializer.save() 时如何创建和修改完整的实例。
  • 序列化器类的字段与 Django Form 类的字段非常相似,包含类似的验证,例如required,max_length 和 default。此外,一些字段还可以控制 serializer 在某些情况下如何显示,比如渲染HTML时,上面的{‘base_template’: ‘textarea.html’} 标志等同于在Django Form类中用widget=widgets.Textarea。这对于控制如何显示可浏览的API特别有用,我们将在本教程的后面看到。
  • 实际上也可以通过使用 ModelSerializer 类来节省一些时间,我们稍后会看到,但是现在我们将使用我们明确定义的 serializer。

四,使用Serializers

在进一步了解之前,我们需要先熟悉使用我们的 Serializer 类。

1,先进入shell

python manage.py shell

2,序列化类的使用演示

>>> from snippet.models import Snippet>>> from snippet.serializers import SnippetSerializer>>> from rest_framework.renderers import JSONRenderer>>> from rest_framework.parsers import JSONParser>>> snippet = Snippet(code=\'foo = \"bar\"\\n\')>>> snippet.save()>>> snippet = Snippet(code=\'print \"hello, world\"\\n\')>>> snippet.save()>>> serializer = SnippetSerializer(snippet)>>> serializer.data{\'id\': 2, \'title\': \'\', \'code\': \'print \"hello, world\"\\n\', \'linenos\': False, \'language\': \'python\', \'style\':\'friendly\'}此时,我们将模型实例转换为 Python 原生数据类型了 结果如下:{\'id\': 2,\'title\': \'\',\'code\': \'print\"hello, world\"\\n\',\'linenos\': False,\'language\': \'python\',\'style\': \'friendly\'}要完成序列化过程,我们还需要将数据渲染成 json 类型。>>> content = JSONRenderer().render(serializer.data)>>> contentb\'{\"id\":2,\"title\":\"\",\"code\":\"print \\\\\"hello, world\\\\\"\\\\n\",\"linenos\":false,\"language\":\"python\",\"style\":\"friendly\"}\'序列化的结果如下:b\'{\"id\": 2,\"title\": \"\",\"code\": \"print \\\\\"hello, world\\\\\"\\\\n\",\"linenos\": false,\"language\": \"python\",\"style\": \"friendly\"}\'
反序列化是类似的。首先需要将一个流解析为 Python 原生数据类型。>>> from django.utils.six import BytesIO>>> stream = BytesIO(content)>>> data = JSONParser().parse(stream)>>> data{\'id\': 2, \'title\': \'\', \'code\': \'print \"hello, world\"\\n\', \'linenos\': False, \'language\': \'python\', \'style\':\'friendly\'}再将得到的 Python 原生数据类型转为模型能使用的字典数据类型>>> serializer = SnippetSerializer(data=data)>>> serializer.is_valid()True>>> serializer.validated_dataOrderedDict([(\'title\', \'\'), (\'code\', \'print \"hello, world\"\'), (\'linenos\', False), (\'language\', \'python\'),(\'style\', \'friendly\')])>>> serializer.save()<Snippet: Snippet object (3)>

在snippet_snippet表中能够找到刚刚的数据记录:

除了可以序列化模型实例外,还能序列化查询集,为此,只需在序列化参数中添加一个 many = True 标志。>>> serializer = SnippetSerializer(Snippet.objects.all(), many=True)>>> serializer.data[OrderedDict([(\'id\', 1), (\'title\', \'\'), (\'code\', \'foo = \"bar\"\\n\'), (\'linenos\', False), (\'language\', \'python\'), (\'style\', \'friendly\')]), OrderedDict([(\'id\', 2), (\'title\', \'\'), (\'code\', \'print \"hello, world\"\\n\'),(\'linenos\', False), (\'language\', \'python\'), (\'style\', \'friendly\')]), OrderedDict([(\'id\', 3), (\'title\', \'\'), (\'code\', \'print \"hello, world\"\'), (\'linenos\', False), (\'language\', \'python\'), (\'style\', \'friendly\')])]结果如下:[OrderedDict([(\'id\',1),(\'title\',\'\'),(\'code\',\'foo=\"bar\"\\n\'),(\'linenos\',False),(\'language\',\'python\'),(\'style\',\'friendly\')]),OrderedDict([(\'id\',2),(\'title\',\'\'),(\'code\',\'print\"hello, world\"\\n\'),(\'linenos\',False),(\'language\',\'python\'),(\'style\',\'friendly\')]),OrderedDict([(\'id\',3),(\'title\',\'\'),(\'code\',\'print\"hello, world\"\'),(\'linenos\',False),(\'language\',\'python\'),(\'style\',\'friendly\')])]

五,使用 ModelSerializers

我们的SnippetSerializer类复制了包含在Snippet模型中的大量信息,。如果我们能让代码更简洁一点就好了。
与Django同时提供表单类和ModelForm类一样,REST框架同时包括序列化器类和ModelSerializer类。

1,使用ModelSerializer创建模型的序列化类

打开文件snippet/serializers.py,然后将SnippetSerializer类替换为以下内容:

class SnippetSerializer(serializers.ModelSerializer):class Meta:model = Snippetfields = (\'id\', \'title\', \'code\', \'linenos\', \'language\', \'style\')

2,序列化类的使用演示

序列化程序一个非常棒的属性就是可以通过打印其结构 (representation) 来检查序列化实例中的所有字段:

>>> from snippet.serializers import SnippetSerializer>>> serializer = SnippetSerializer()>>> print(repr(serializer))SnippetSerializer():id = IntegerField(read_only=True)title = CharField(allow_blank=True, max_length=100, required=False)code = CharField(style={\'base_template\': \'textarea.html\'})linenos = BooleanField(required=False)language = ChoiceField(choices=[(\'abap\', \'ABAP\'), (\'abnf\', \'ABNF\'), (\'ada\', \'Ada\'), (\'adl\', \'ADL\'), (\'agda\', \'Agda\'), (\'aheui\', \'Aheui\'), (\'ahk\', \'autohotkey\'), (\'alloy\', \'Alloy\'), (\'ampl\', \'Ampl\'), (\'antlr\', \'ANTLR\'), (\'antlr-as\', \'ANTLR With ActionScript Target\'), (\'antlr-cpp\', \'ANTLR With CPP Target\'), (\'antlr-csharp\', \'ANTLR With C# Target\'), (\'antlr-java\', \'ANTLR With Java Target\'), (\'antlr-objc\', \'ANTLR With ObjectiveC Target\'), (\'antlr-perl\', \'ANTLR With Perl Target\'), (\'antlr-python\', \'ANTLR With Python Target\'), (\'antlr-ruby\', \'ANTLR With Ruby Target\'), (\'apacheconf\', \'ApacheConf\'), (\'apl\', \'APL\'), (\'applescript\', \'AppleScript\'), (\'arduino\', \'Arduino\'), (\'as\', \'ActionScript\'), (\'as3\', \'ActionScript 3\'), (\'aspectj\', \'AspectJ\'), (\'aspx-cs\', \'aspx-cs\'), (\'aspx-vb\', \'aspx-vb\'), (\'asy\', \'Asymptote\'), (\'at\', \'AmbientTalk\'), (\'augeas\', \'Augeas\'), (\'autoit\', \'AutoIt\'), (\'awk\', \'Awk\'), (\'basemake\', \'Base Makefile\'), (\'bash\', \'Bash\'), (\'bat\', \'Batchfile\'), (\'bbcbasic\', \'BBC Basic\'), (\'bbcode\', \'BBCode\'), (\'bc\', \'BC\'), (\'befunge\', \'Befunge\'), (\'bib\', \'BibTeX\'), (\'blitzbasic\', \'BlitzBasic\'), (\'blitzmax\', \'BlitzMax\'), (\'bnf\', \'BNF\'), (\'boa\', \'Boa\'), (\'boo\', \'Boo\'), (\'boogie\', \'Boogie\'), (\'brainfuck\', \'Brainfuck\'), (\'bst\', \'BST\'), (\'bugs\', \'BUGS\'), (\'c\', \'C\'), (\'c-objdump\', \'c-objdump\'), (\'ca65\', \'ca65 assembler\'), (\'cadl\', \'cADL\'), (\'camkes\',\'CAmkES\'), (\'capdl\', \'CapDL\'), (\'capnp\', \"Cap\'n Proto\"), (\'cbmbas\', \'CBM BASIC V2\'), (\'ceylon\', \'Ceylon\'), (\'cfc\', \'Coldfusion CFC\'), (\'cfengine3\', \'CFEngine3\'), (\'cfm\', \'Coldfusion HTML\'), (\'cfs\', \'cfstatement\'), (\'chai\', \'ChaiScript\'), (\'chapel\', \'Chapel\'), (\'charmci\', \'Charmci\'), (\'cheetah\', \'Cheetah\'), (\'cirru\', \'Cirru\'), (\'clay\', \'Clay\'), (\'clean\', \'Clean\'), (\'clojure\', \'Clojure\'), (\'clojurescript\', \'ClojureScript\'), (\'cmake\', \'CMake\'), (\'cobol\', \'COBOL\'), (\'cobolfree\', \'COBOLFree\'), (\'coffee-script\', \'CoffeeScript\'), (\'common-lisp\', \'Common Lisp\'), (\'componentpascal\', \'Component Pascal\'), (\'console\', \'Bash Session\'),(\'control\', \'Debian Control file\'), (\'coq\', \'Coq\'), (\'cpp\', \'C++\'), (\'cpp-objdump\', \'cpp-objdump\'), (\'cpsa\', \'CPSA\'), (\'cr\', \'Crystal\'), (\'crmsh\', \'Crmsh\'), (\'croc\', \'Croc\'), (\'cryptol\', \'Cryptol\'), (\'csharp\',\'C#\'), (\'csound\', \'Csound Orchestra\'), (\'csound-document\', \'Csound Document\'), (\'csound-score\', \'CsoundScore\'), (\'css\', \'CSS\'), (\'css+django\', \'CSS+Django/Jinja\'), (\'css+erb\', \'CSS+Ruby\'), (\'css+genshitext\',\'CSS+Genshi Text\'), (\'css+lasso\', \'CSS+Lasso\'), (\'css+mako\', \'CSS+Mako\'), (\'css+mozpreproc\', \'CSS+mozpreproc\'), (\'css+myghty\', \'CSS+Myghty\'), (\'css+php\', \'CSS+PHP\'), (\'css+smarty\', \'CSS+Smarty\'), (\'cucumber\', \'Gherkin\'), (\'cuda\', \'CUDA\'), (\'cypher\', \'Cypher\'), (\'cython\', \'Cython\'), (\'d\', \'D\'), (\'d-objdump\', \'d-objdump\'), (\'dart\', \'Dart\'), (\'dasm16\', \'DASM16\'), (\'delphi\', \'Delphi\'), (\'dg\', \'dg\'), (\'diff\', \'Diff\'), (\'django\', \'Django/Jinja\'), (\'docker\', \'Docker\'), (\'doscon\', \'MSDOS Session\'), (\'dpatch\', \'Darcs Patch\'), (\'dtd\', \'DTD\'), (\'duel\', \'Duel\'), (\'dylan\', \'Dylan\'), (\'dylan-console\', \'Dylan session\'), (\'dylan-lid\', \'DylanLID\'), (\'earl-grey\', \'Earl Grey\'), (\'easytrieve\', \'Easytrieve\'), (\'ebnf\', \'EBNF\'), (\'ec\', \'eC\'), (\'ecl\', \'ECL\'), (\'eiffel\', \'Eiffel\'), (\'elixir\', \'Elixir\'), (\'elm\', \'Elm\'), (\'emacs\', \'EmacsLisp\'), (\'email\',\'E-mail\'), (\'erb\', \'ERB\'), (\'erl\', \'Erlang erl session\'), (\'erlang\', \'Erlang\'), (\'evoque\', \'Evoque\'), (\'extempore\', \'xtlang\'), (\'ezhil\', \'Ezhil\'), (\'factor\', \'Factor\'), (\'fan\', \'Fantom\'), (\'fancy\', \'Fancy\'), (\'felix\', \'Felix\'), (\'fennel\', \'Fennel\'), (\'fish\', \'Fish\'), (\'flatline\', \'Flatline\'), (\'floscript\', \'FloScript\'), (\'forth\', \'Forth\'), (\'fortran\', \'Fortran\'), (\'fortranfixed\', \'FortranFixed\'), (\'foxpro\', \'FoxPro\'), (\'freefem\', \'Freefem\'), (\'fsharp\', \'F#\'), (\'gap\', \'GAP\'), (\'gas\', \'GAS\'), (\'genshi\', \'Genshi\'), (\'genshitext\', \'Genshi Text\'), (\'glsl\', \'GLSL\'), (\'gnuplot\', \'Gnuplot\'), (\'go\', \'Go\'), (\'golo\', \'Golo\'), (\'gooddata-cl\', \'GoodData-CL\'), (\'gosu\', \'Gosu\'), (\'groff\', \'Groff\'), (\'groovy\', \'Groovy\'), (\'gst\', \'Gosu Template\'), (\'haml\', \'Haml\'), (\'handlebars\', \'Handlebars\'), (\'haskell\', \'Haskell\'), (\'haxeml\', \'Hxml\'), (\'hexdump\', \'Hexdump\'), (\'hlsl\', \'HLSL\'), (\'hsail\', \'HSAIL\'), (\'hspec\', \'Hspec\'), (\'html\', \'HTML\'), (\'html+cheetah\', \'HTML+Cheetah\'), (\'html+django\', \'HTML+Django/Jinja\'), (\'html+evoque\', \'HTML+Evoque\'), (\'html+genshi\', \'HTML+Genshi\'), (\'html+handlebars\', \'HTML+Handlebars\'), (\'html+lasso\', \'HTML+Lasso\'), (\'html+mako\', \'HTML+Mako\'), (\'html+myghty\', \'HTML+Myghty\'), (\'html+ng2\', \'HTML + Angular2\'), (\'html+php\', \'HTML+PHP\'), (\'html+smarty\', \'HTML+Smarty\'), (\'html+twig\', \'HTML+Twig\'), (\'html+velocity\', \'HTML+Velocity\'), (\'http\', \'HTTP\'), (\'hx\', \'Haxe\'), (\'hybris\', \'Hybris\'), (\'hylang\', \'Hy\'), (\'i6t\', \'Inform 6 template\'), (\'icon\', \'Icon\'), (\'idl\', \'IDL\'), (\'idris\', \'Idris\'), (\'iex\', \'Elixir iex session\'), (\'igor\', \'Igor\'), (\'inform6\', \'Inform 6\'), (\'inform7\', \'Inform 7\'), (\'ini\', \'INI\'), (\'io\', \'Io\'), (\'ioke\', \'Ioke\'), (\'irc\', \'IRC logs\'),(\'isabelle\', \'Isabelle\'), (\'j\', \'J\'), (\'jags\', \'JAGS\'), (\'jasmin\', \'Jasmin\'), (\'java\', \'Java\'), (\'javascript+mozpreproc\', \'Javascript+mozpreproc\'), (\'jcl\', \'JCL\'), (\'jlcon\', \'Julia console\'), (\'js\', \'JavaScript\'), (\'js+cheetah\', \'JavaScript+Cheetah\'), (\'js+django\', \'JavaScript+Django/Jinja\'), (\'js+erb\', \'JavaScript+Ruby\'), (\'js+genshitext\', \'JavaScript+Genshi Text\'), (\'js+lasso\', \'JavaScript+Lasso\'), (\'js+mako\', \'JavaScript+Mako\'), (\'js+myghty\', \'JavaScript+Myghty\'), (\'js+php\', \'JavaScript+PHP\'), (\'js+smarty\', \'JavaScript+Smarty\'), (\'jsgf\', \'JSGF\'), (\'json\', \'JSON\'), (\'json-object\', \'JSONBareObject\'), (\'jsonld\', \'JSON-LD\'), (\'jsp\', \'Java Server Page\'), (\'julia\', \'Julia\'), (\'juttle\', \'Juttle\'), (\'kal\', \'Kal\'), (\'kconfig\', \'Kconfig\'), (\'kmsg\', \'Kernel log\'), (\'koka\', \'Koka\'), (\'kotlin\', \'Kotlin\'), (\'lagda\', \'Literate Agda\'), (\'lasso\', \'Lasso\'), (\'lcry\', \'Literate Cryptol\'), (\'lean\', \'Lean\'), (\'less\', \'LessCss\'), (\'lhs\', \'Literate Haskell\'), (\'lidr\', \'Literate Idris\'), (\'lighty\', \'Lighttpd configuration file\'), (\'limbo\', \'Limbo\'), (\'liquid\', \'liquid\'), (\'live-script\', \'LiveScript\'), (\'llvm\', \'LLVM\'), (\'llvm-mir\', \'LLVM-MIR\'), (\'llvm-mir-body\', \'LLVM-MIR Body\'), (\'logos\', \'Logos\'), (\'logtalk\', \'Logtalk\'), (\'lsl\', \'LSL\'), (\'lua\', \'Lua\'), (\'make\', \'Makefile\'), (\'mako\', \'Mako\'), (\'maql\', \'MAQL\'), (\'mask\', \'Mask\'), (\'mason\', \'Mason\'), (\'mathematica\',\'Mathematica\'), (\'matlab\', \'Matlab\'), (\'matlabsession\', \'Matlab session\'), (\'md\', \'markdown\'), (\'mime\', \'MIME\'), (\'minid\', \'MiniD\'), (\'modelica\', \'Modelica\'), (\'modula2\', \'Modula-2\'), (\'monkey\', \'Monkey\'), (\'monte\', \'Monte\'), (\'moocode\', \'MOOCode\'), (\'moon\', \'MoonScript\'), (\'mosel\', \'Mosel\'), (\'mozhashpreproc\', \'mozhashpreproc\'), (\'mozpercentpreproc\', \'mozpercentpreproc\'), (\'mql\', \'MQL\'), (\'ms\', \'MiniScript\'), (\'mscgen\', \'Mscgen\'), (\'mupad\', \'MuPAD\'), (\'mxml\', \'MXML\'), (\'myghty\', \'Myghty\'), (\'mysql\', \'MySQL\'), (\'nasm\',\'NASM\'), (\'ncl\', \'NCL\'), (\'nemerle\', \'Nemerle\'), (\'nesc\', \'nesC\'), (\'newlisp\', \'NewLisp\'), (\'newspeak\', \'Newspeak\'), (\'ng2\', \'Angular2\'), (\'nginx\', \'Nginx configuration file\'), (\'nim\', \'Nimrod\'), (\'nit\', \'Nit\'), (\'nixos\', \'Nix\'), (\'notmuch\', \'Notmuch\'), (\'nsis\', \'NSIS\'), (\'numpy\', \'NumPy\'), (\'nusmv\', \'NuSMV\'), (\'objdump\', \'objdump\'), (\'objdump-nasm\', \'objdump-nasm\'), (\'objective-c\', \'Objective-C\'), (\'objective-c++\',\'Objective-C++\'), (\'objective-j\', \'Objective-J\'), (\'ocaml\', \'OCaml\'), (\'octave\', \'Octave\'), (\'odin\', \'ODIN\'), (\'ooc\', \'Ooc\'), (\'opa\', \'Opa\'), (\'openedge\', \'OpenEdge ABL\'), (\'pacmanconf\', \'PacmanConf\'), (\'pan\',\'Pan\'), (\'parasail\', \'ParaSail\'), (\'pawn\', \'Pawn\'), (\'peg\', \'PEG\'), (\'perl\', \'Perl\'), (\'perl6\', \'Perl6\'),(\'php\', \'PHP\'), (\'pig\', \'Pig\'), (\'pike\', \'Pike\'), (\'pkgconfig\', \'PkgConfig\'), (\'plpgsql\', \'PL/pgSQL\'), (\'pony\', \'Pony\'), (\'postgresql\', \'PostgreSQL SQL dialect\'), (\'postscript\', \'PostScript\'), (\'pot\', \'GettextCatalog\'), (\'pov\', \'POVRay\'), (\'powershell\', \'PowerShell\'), (\'praat\', \'Praat\'), (\'prolog\', \'Prolog\'), (\'properties\', \'Properties\'), (\'protobuf\', \'Protocol Buffer\'), (\'ps1con\', \'PowerShell Session\'), (\'psql\', \'PostgreSQL console (psql)\'), (\'pug\', \'Pug\'), (\'puppet\', \'Puppet\'), (\'py2tb\', \'Python 2.x Traceback\'), (\'pycon\', \'Python console session\'), (\'pypylog\', \'PyPy Log\'), (\'pytb\', \'Python Traceback\'), (\'python\', \'Python\'), (\'python2\', \'Python 2.x\'), (\'qbasic\', \'QBasic\'), (\'qml\', \'QML\'), (\'qvto\', \'QVTO\'), (\'racket\', \'Racket\'), (\'ragel\', \'Ragel\'), (\'ragel-c\', \'Ragel in C Host\'), (\'ragel-cpp\', \'Ragel in CPP Host\'), (\'ragel-d\',\'Ragel in D Host\'), (\'ragel-em\', \'Embedded Ragel\'), (\'ragel-java\', \'Ragel in Java Host\'), (\'ragel-objc\',\'Ragel in Objective C Host\'), (\'ragel-ruby\', \'Ragel in Ruby Host\'), (\'raw\', \'Raw token data\'), (\'rb\', \'Ruby\'), (\'rbcon\', \'Ruby irb session\'), (\'rconsole\', \'RConsole\'), (\'rd\', \'Rd\'), (\'reason\', \'ReasonML\'), (\'rebol\', \'REBOL\'), (\'red\', \'Red\'), (\'redcode\', \'Redcode\'), (\'registry\', \'reg\'), (\'resource\', \'ResourceBundle\'), (\'rexx\', \'Rexx\'), (\'rhtml\', \'RHTML\'), (\'ride\', \'Ride\'), (\'rnc\', \'Relax-NG Compact\'), (\'roboconf-graph\', \'Roboconf Graph\'), (\'roboconf-instances\', \'Roboconf Instances\'), (\'robotframework\', \'RobotFramework\'), (\'rql\', \'RQL\'), (\'rsl\', \'RSL\'), (\'rst\', \'reStructuredText\'), (\'rts\', \'TrafficScript\'), (\'rust\', \'Rust\'), (\'sarl\', \'SARL\'), (\'sas\', \'SAS\'), (\'sass\', \'Sass\'), (\'sc\', \'SuperCollider\'), (\'scala\', \'Scala\'), (\'scaml\', \'Scaml\'), (\'scdoc\', \'scdoc\'), (\'scheme\', \'Scheme\'), (\'scilab\', \'Scilab\'), (\'scss\', \'SCSS\'), (\'sgf\', \'SmartGameFormat\'), (\'shen\', \'Shen\'), (\'shexc\', \'ShExC\'), (\'sieve\', \'Sieve\'), (\'silver\', \'Silver\'), (\'slash\', \'Slash\'), (\'slim\', \'Slim\'), (\'slurm\', \'Slurm\'), (\'smali\', \'Smali\'), (\'smalltalk\', \'Smalltalk\'), (\'smarty\', \'Smarty\'), (\'sml\', \'Standard ML\'), (\'snobol\', \'Snobol\'), (\'snowball\', \'Snowball\'), (\'solidity\', \'Solidity\'), (\'sourceslist\', \'Debian Sourcelist\'), (\'sp\', \'SourcePawn\'), (\'sparql\', \'SPARQL\'), (\'spec\', \'RPMSpec\'), (\'splus\', \'S\'), (\'sql\', \'SQL\'), (\'sqlite3\', \'sqlite3con\'), (\'squidconf\', \'SquidConf\'), (\'ssp\', \'Scalate Server Page\'), (\'stan\', \'Stan\'), (\'stata\', \'Stata\'), (\'swift\', \'Swift\'), (\'swig\', \'SWIG\'), (\'systemverilog\', \'systemverilog\'), (\'tads3\', \'TADS 3\'), (\'tap\', \'TAP\'), (\'tasm\', \'TASM\'), (\'tcl\', \'Tcl\'), (\'tcsh\', \'Tcsh\'), (\'tcshcon\', \'Tcsh Session\'), (\'tea\', \'Tea\'), (\'termcap\', \'Termcap\'), (\'terminfo\', \'Terminfo\'), (\'terraform\', \'Terraform\'), (\'tex\', \'TeX\'), (\'text\', \'Text only\'), (\'thrift\', \'Thrift\'), (\'todotxt\', \'Todotxt\'), (\'toml\', \'TOML\'), (\'trac-wiki\', \'MoinMoin/Trac Wiki markup\'), (\'treetop\', \'Treetop\'), (\'ts\', \'TypeScript\'), (\'tsql\', \'Transact-SQL\'), (\'ttl\', \'Tera Term macro\'), (\'turtle\', \'Turtle\'), (\'twig\', \'Twig\'), (\'typoscript\', \'TypoScript\'), (\'typoscriptcssdata\', \'TypoScriptCssData\'), (\'typoscripthtmldata\', \'TypoScriptHtmlData\'), (\'ucode\', \'ucode\'), (\'unicon\', \'Unicon\'), (\'urbiscript\', \'UrbiScript\'), (\'usd\', \'USD\'),(\'vala\', \'Vala\'), (\'vb.net\', \'VB.net\'), (\'vbscript\', \'VBScript\'), (\'vcl\', \'VCL\'), (\'vclsnippets\', \'VCLSnippets\'), (\'vctreestatus\', \'VCTreeStatus\'), (\'velocity\', \'Velocity\'), (\'verilog\', \'verilog\'), (\'vgl\', \'VGL\'), (\'vhdl\', \'vhdl\'), (\'vim\', \'VimL\'), (\'wdiff\', \'WDiff\'), (\'webidl\', \'Web IDL\'), (\'whiley\', \'Whiley\'),(\'x10\', \'X10\'), (\'xml\', \'XML\'), (\'xml+cheetah\', \'XML+Cheetah\'), (\'xml+django\', \'XML+Django/Jinja\'), (\'xml+erb\', \'XML+Ruby\'), (\'xml+evoque\', \'XML+Evoque\'), (\'xml+lasso\', \'XML+Lasso\'), (\'xml+mako\', \'XML+Mako\'), (\'xml+myghty\', \'XML+Myghty\'), (\'xml+php\', \'XML+PHP\'), (\'xml+smarty\', \'XML+Smarty\'), (\'xml+velocity\', \'XML+Velocity\'), (\'xorg.conf\', \'Xorg\'), (\'xquery\', \'XQuery\'), (\'xslt\', \'XSLT\'), (\'xtend\', \'Xtend\'), (\'xul+mozpreproc\', \'XUL+mozpreproc\'), (\'yaml\', \'YAML\'), (\'yaml+jinja\', \'YAML+Jinja\'), (\'zeek\', \'Zeek\'), (\'zephir\',\'Zephir\'), (\'zig\', \'Zig\')], default=\'python\')style = ChoiceField(choices=[(\'abap\', \'abap\'), (\'algol\', \'algol\'), (\'algol_nu\', \'algol_nu\'), (\'arduino\', \'arduino\'), (\'autumn\', \'autumn\'), (\'borland\', \'borland\'), (\'bw\', \'bw\'), (\'colorful\', \'colorful\'), (\'default\', \'default\'), (\'emacs\', \'emacs\'), (\'friendly\', \'friendly\'), (\'fruity\', \'fruity\'), (\'igor\', \'igor\'), (\'inkpot\', \'inkpot\'), (\'lovelace\', \'lovelace\'), (\'manni\', \'manni\'), (\'monokai\', \'monokai\'), (\'murphy\',\'murphy\'), (\'native\', \'native\'), (\'paraiso-dark\', \'paraiso-dark\'), (\'paraiso-light\', \'paraiso-light\'), (\'pastie\', \'pastie\'), (\'perldoc\', \'perldoc\'), (\'rainbow_dash\', \'rainbow_dash\'), (\'rrt\', \'rrt\'), (\'sas\', \'sas\'), (\'solarized-dark\', \'solarized-dark\'), (\'solarized-light\', \'solarized-light\'), (\'stata\', \'stata\'), (\'stata-dark\', \'stata-dark\'), (\'stata-light\', \'stata-light\'), (\'tango\', \'tango\'), (\'trac\', \'trac\'), (\'vim\',\'vim\'), (\'vs\', \'vs\'), (\'xcode\', \'xcode\')], default=\'friendly\')

与 Serializer 类相比,ModelSerializer 类并不会做任何特别神奇的事情,它只是创建序列化器类的快捷方式:

  • 自动确定一组字段(不用重复去定义类属性)。
  • 默认简单实现的 create() 和 update() 方法。

3,编写序列化功能视图

编辑 snippets/views.py 文件,并且添加以下内容。

from django.http import HttpResponse, JsonResponsefrom django.views.decorators.csr20000f import csrf_exemptfrom rest_framework.renderers import JSONRendererfrom rest_framework.parsers import JSONParserfrom snippet.models import Snippetfrom snippet.serializers import SnippetSerializerfrom rest_framework.response import Responsefrom rest_framework.decorators import api_view# Create your views here.API 的根视图支持列出所有现有的 snippet 或创建一个新的 snippet。@csrf_exempt@api_view([\'GET\', \'POST\'])def snippet_list(request):\"\"\"列出所有的代码 snippet,或创建一个新的 snippet。\"\"\"if request.method == \'GET\':snippets = Snippet.objects.all().order_by(\'id\')serializer = SnippetSerializer(snippets, many=True)return JsonResponse(serializer.data, safe=False)elif request.method == \'POST\':data = JSONParser().parse(request)serializer = SnippetSerializer(data=data)if serializer.is_valid():serializer.save()return JsonResponse(serializer.data, status=201)return JsonResponse(serializer.errors, status=400)还需要一个与单个 snippet 相对应的视图,并可用于检索,更新或删除 snippet。@csrf_exemptdef snippet_detail(request, pk):\"\"\"获取,更新或删除一个代码 snippet\"\"\"try:snippet = Snippet.objects.get(pk=pk)except Snippet.DoesNotExist:return HttpResponse(status=404)if request.method == \'GET\':q = Snippet.objects.all().order_by(\'id\')seializer = SnippetSerializer(q, many=True)return Response(seializer.data)# if request.method == \'GET\':#    snippets = Snippet.objects.all()#    serializer = SnippetSerializer(snippets, many=True)#    return JsonResponse(serializer.data, safe=False)elif request.method == \'PUT\':data = JSONParser().parse(request)serializer = SnippetSerializer(snippet, data=data)if serializer.is_valid():serializer.save()return JsonResponse(serializer.data)return JsonResponse(serializer.errors, status=400)elif request.method == \'DELETE\':snippet.delete()return HttpResponse(status=204)

4,编写路由信息

snippet/urls.py 文件:from django.conf.urls import urlfrom snippets import viewsurlpatterns = [url(r\'^snippets/$\', views.snippet_list),url(r\'^snippets/(?P<pk>[0-9]+)/$\', views.snippet_detail),]tutorial/urls.py 文件:from django.conf.urls import url, includeurlpatterns = [url(r\'^\', include(\'snippets.urls\')),]

5,运行


赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Django Rest Framework的基础组件使用方法之序列化:一个简单的案例