Transforming model instances into other formats such as JSON or XML is a core capability needed when exposing APIs or exchanging data between systems. In Django, the built-in django.core.serializers module provides a straightforward way to convert querysets into serialized representations with out requiring extra dependencies.
Basic Usage
To produce a serialized output, import the module and call serialize() with the desired format name and a queryset. Valid formats include json and xml.
from django.core import serializers
records = serializers.serialize("json", Author.objects.all())
print(records)
The returned string contains a list of objects, each holding the model identifier, primary key, and a fields dictionary of attribute values.
[
{
"model": "index.author",
"pk": 2,
"fields": {
"name": "pfeiliu",
"age": 19,
"email": "789@163.com",
"is_active": false
}
}
]
Limiting the Exported Fields
When you only need a subset of a model’s fields, provide the fields keyword argument as a tuple of attribute names:
selection = serializers.serialize(
"xml",
Author.objects.only("name", "age"),
fields=("name", "age")
)
print(selection)
For JSON output, the same approach applies:
partial_data = serializers.serialize(
"json",
Author.objects.all(),
fields=("name", "age")
)
print(partial_data)
The resulting structure still includes model and pk, but fields will contain only the keys specified.
[
{
"model": "index.author",
"pk": 2,
"fields": {
"name": "pfeiliu",
"age": 19
}
}
]
Deserialization and Reconstructing Objects
Serialization is only one direction. To recreate model instances from a serialized stream, use deserialize:
for deserialized_object in serializers.deserialize("json", json_data):
deserialized_object.save()
Each iteration yields a DeserializedObject that wraps the model instance, allowing bulk operations or individual saving.