- Building RESTful Python Web Services
- Gastón C. Hillar
- 350字
- 2021-08-20 10:24:24
Using model serializers to eliminate duplicate code
The GameSerializer
class declares many attributes with the same names that we used in the Game
model and repeats information, such as the types and the max_length
values. The GameSerializer
class is a subclass of rest_framework.serializers.Serializer
, it declares attributes that we manually mapped to the appropriate types and overrides the create
and update
methods.
Now, we will create a new version of the GameSerializer
class that will inherit from the rest_framework.serializers.ModelSerializer
class. The ModelSerializer
class automatically populates both set of default fields and a set of default validators. In addition, the class provides default implementations for the create
and update
methods.
Tip
In case you have any experience with Django Web Framework, you will notice that the Serializer
and ModelSerializer
classes are similar to the Form
and ModelForm
classes.
Now, go to the gamesapi/games
folder and open the serializers.py
file. Replace the code in this file with the following code, that declares the new version of the GameSerializer
class. The code file for the sample is included in the restful_python_chapter_02_01
folder:
from rest_framework import serializers from games.models import Game class GameSerializer(serializers.ModelSerializer): class Meta: model = Game fields = ('id', 'name', 'release_date', 'game_category', 'played')
The new GameSerializer
class declares a Meta
inner class that declares two attributes: model
and fields
. The model
attribute specifies the model related to the serializer, that is, the Game
class. The fields
attribute specifies a tuple of string whose values indicate the field names that we want to include in the serialization from the related model.
There is no need to override either create
or update
methods because the generic behavior will be enough in this case. The ModelSerializer
superclass provides implementations for both methods.
We have reduced the boilerplate code that we didn't require in the GameSerializer
class. We just needed to specify the desired set of fields in a tuple. Now, the types related to the game fields are included only in the Game
class.
Tip
Press Ctrl + C to quit Django's development server and execute the following command to start it again:
python manage.py runserver
- Kibana Essentials
- ReSharper Essentials
- 深入淺出Spring Boot 2.x
- 青少年美育趣味課堂:XMind思維導(dǎo)圖制作
- Programming ArcGIS 10.1 with Python Cookbook
- Visual Basic程序設(shè)計(jì)與應(yīng)用實(shí)踐教程
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第2版)(微課版)
- 深入理解Elasticsearch(原書第3版)
- 青少年學(xué)Python(第1冊(cè))
- 軟件品質(zhì)之完美管理:實(shí)戰(zhàn)經(jīng)典
- Unity 2D Game Development Cookbook
- Hands-On Kubernetes on Windows
- Offer來了:Java面試核心知識(shí)點(diǎn)精講(框架篇)
- Ubuntu Server Cookbook
- Natural Language Processing with Python Cookbook