Understanding django serializers with examples

Reading Time : ~ .

Serializers are used for “translating” Django models into other formats like xmi,json,yaml(YAML Ain’t a Markup Language)

from django.core import serializers

data = serializers.serialize("xml", SomeModel.objects.all())

the first argument will be the format we want to serialize the data and second will be a QuerySet to serialize.

we can also translate using a serializer object directly

XMLSerializer = serializers.get_serializer("xml")

xml_serializer = XMLSerializer()

xml_serializer.serialize(queryset)

data = xml_serializer.getvalue()

this is useful when we want data directly be a file like object.

we can also translate only subset of fields using fields argument 

from django.core import serializers

data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size')) class Teacher(models.Model):

    name = models.CharField(max_length=50)

    qualification = models.CharField(max_length=50)        

class College(Teacher):

    name = models.models.CharField(max_length=50)

for the inherited models,to translate child class objects we have to list all parent class objects and child class objects into single list,then translate.

all_objects = list(Teacher.objects.all()) + list(College.objects.all())

data = serializers.serialize('xml', all_objects)

Deserializing data:

for obj in serializers.deserialize("xml", data):
    do_something_with(obj)

it will take same arguments as serialize function and returns an iterator

The objects returned by the deserialize iterator are unsavedobjects and Calling DeserializedObject.save() saves the object to the database.


for deserialized_object in serializers.deserialize("xml", data):

    if object_should_be_saved(deserialized_object):

        deserialized_object.save()
    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Sendgrid Inbound Email Parsing with django Nikhila Mergu

Using the Inbound parse webhook, we can parse the contents, attachments of an incoming email.

Inbound Parse API follows 3 steps:
1. sending an ...

Continue Reading...
Setting Up Coveralls for Django Project Ravi Kumar Gadila

Coveraslls will check the code coverage for your test cases. To use coveralls.io your code must be hosted on GitHub or BitBucket.

install coveralls
...

Continue Reading...
Creating Django App Siva Chittamuru

Django is a high-level, free and open-source Python Web framework that encourages rapid development. Django follows the model–view–controller (MVC) architectural pattern. Django's primary goal is ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties