SERIALIZERS.
The Django Rest Framework provides powerful model
serialization, display data using standard function based views, or get
granular with powerful class based views for more complex functionality.
Serialization can simply be defined as what allows complex data such as querysets,
and model instances to be converted to native Python datatypes that can then be
easily rendered into
JSON
,
XML
or other content
types, and the reconversion to the complex version is referred to as deserialization).
Let’s see how to
declare serializers:
# first let’s import serializers
from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
email =
serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
#The above class
defines the fields that gets serialized/deserialized. The above looks similar
to declaring a form.
The serializers works basically
based on Modelserializers class and HyperLinkedModelSerializers class.
The Modelserializers class
lets you automatically create a Serializer class with fields that correspond to
the Model fields, while HyperLinkedModelSerializers
class which is similar to the
ModelSerializer
class uses hyperlinks to represent relationships, rather than primary keys.
For
instance, for a model say
class Account(models.Model):
account_name = models.CharField()
users = models.CharField()
created = models.BooleanField()
address = models.CharField()
Email = models.EmailField()
Modelserializer class for the model Account will look like
this.
from rest_framework import
serializers
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
While for the HyperLinkedModelSerializers
class, we will have something like this:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = ('url', 'id', 'account_name', 'users', 'created')
url
field
instead of a primary key field.The url field will be represented using a
HyperlinkedIdentityField
serializer field, and any relationships on the model will be represented using
a HyperlinkedRelatedField
serializer field.THIS IS JUST PART A OF DJANGO REST FRAMEWORK( Serializers), I will be back for the other part later. If you want another part of this post, or if this post was helpful in any way please leave your comment below.
Thanks for reading, I love U.
source(wiki,django RestFrameWork doc,me)
Django Rest FrameWork : SERIALIZERS
Reviewed by Unknown
on
08:26
Rating:
No comments: