dumpdata
management command.serialize
function are the format to serialize the datato (see Serialization formats) and aQuerySet
to serialize. (Actually, the secondargument can be any iterator that yields Django model instances, but it’llalmost always be a QuerySet).django.core.serializers.
get_serializer
(format)¶HttpResponse
):get_serializer()
with an unknownformat will raise adjango.core.serializers.SerializerDoesNotExist
exception.fields
argument to the serializer:name
and size
attributes of each model willbe serialized. The primary key is always serialized as the pk
element in theresulting output; it never appears in the fields
part.serves_hot_dogs
attribute. The name
attribute of the base class will be ignored.Restaurant
instances, you will need toserialize the Place
models as well:deserialize
function takes the same format argument asserialize
, a string or stream of data, and returns an iterator.deserialize
iterator aren’t regular Django objects. Instead, they arespecial DeserializedObject
instances that wrap a created – but unsaved –object and any associated relationship data.DeserializedObject.save()
saves the object to the database.pk
attribute in the serialized data doesn’t exist or isnull, a new instance will be saved to the database.DeserializedObject
instances lookssomething like:deserialized_object.object
.If fields in the serialized data do not exist on a model, aDeserializationError
will be raised unless the ignorenonexistent
argument is passed in as True
:Identifier | Information |
---|---|
xml | Serializes to and from a simple XML dialect. |
json | Serializes to and from JSON. |
yaml | Serializes to YAML (YAML Ain’t a Markup Language). Thisserializer is only available if PyYAML is installed. |
<django-objects>
-tag which contains multiple<object>
-elements. Each such object has two attributes: “pk” and “model”,the latter being represented by the name of the app (“sessions”) and thelowercase name of the model (“session”) separated by a dot.<field>
-element sporting thefields “type” and “name”. The text content of the element represents the valuethat should be stored.auth.Permission
object with the PK 27has a foreign key to the contenttypes.ContentType
instance with the PK 9.auth.User
model has such a relation to the auth.Permission
model:ValueError
exception. Read also the W3C’s explanation of HTML,XHTML, XML and Control Codes.json
.For example, if you have some custom type in an object to be serialized, you’llhave to write a custom json
encoder for it. Something like this willwork:cls=LazyEncoder
to the serializers.serialize()
function:DjangoJSONEncoder
¶django.core.serializers.json.
DjangoJSONEncoder
¶DjangoJSONEncoder
for encoding. A subclass ofJSONEncoder
, it handles these additional types:datetime
YYYY-MM-DDTHH:mm:ss.sssZ
orYYYY-MM-DDTHH:mm:ss.sss+HH:MM
as defined in ECMA-262.date
YYYY-MM-DD
as defined in ECMA-262.time
HH:MM:ss.sss
as defined in ECMA-262.timedelta
timedelta(days=1,hours=2,seconds=3.4)
is represented as'P1DT02H00M03.400000S'
.Decimal
, Promise
(django.utils.functional.lazy()
objects), UUID
ContentType
. If you’re going toserialize an object that refers to a content type, then you need to have a wayto refer to that content type to begin with. Since ContentType
objects areautomatically created by Django during the database synchronization process,the primary key of a given content type isn’t easy to predict; it willdepend on how and when migrate
was executed. This is true for allmodels which automatically generate objects, notably includingPermission
,Group
, andUser
.IntegrityError
.Book
would use an integer to refer tothe author. For example, in JSON, a Book might be serialized as:get_by_natural_key()
method. In the caseof a Person, a good natural key might be the pair of first and lastname:Person
objects:get_by_natural_key()
method to resolve ['Douglas','Adams']
into the primary key of an actual Person
object.unique_together
over multiple fields) for the field or fieldsin your natural key. However, uniqueness doesn’t need to beenforced at the database level. If you are certain that a set offields will be effectively unique, you can still use those fieldsas a natural key.get_by_natural_key()
method and if so, use it topopulate the deserialized object’s primary key.(firstname,lastname)
. Then, when you callserializers.serialize()
, you provide use_natural_foreign_keys=True
or use_natural_primary_keys=True
arguments:use_natural_foreign_keys=True
is specified, Django will use thenatural_key()
method to serialize any foreign key reference to objectsof the type that defines the method.use_natural_primary_keys=True
is specified, Django will not provide theprimary key in the serialized data of this object since it can be calculatedduring deserialization:dumpdata
to generate serialized data, use thedumpdata--natural-foreign
and dumpdata--natural-primary
command line flags to generate natural keys.natural_key()
andget_by_natural_key()
. If you don’t want Django to outputnatural keys during serialization, but you want to retain theability to load natural keys, then you can opt to not implementthe natural_key()
method.get_by_natural_key()
method.handle_forward_references=True
to serializers.deserialize()
. This willset the deferred_fields
attribute on the DeserializedObject
instances.You’ll need to keep track of DeserializedObject
instances where thisattribute isn’t None
and later call save_deferred_fields()
on them.ForeignKey
on the referencing model must havenull=True
.dumpdata
that use the dumpdata--natural-foreign
option will serialize any model with a natural_key()
method before serializing standard primary key objects.natural_key()
methods. You do this by setting a dependencies
attribute on the natural_key()
method itself.Book
model from theexample above:Book
is a combination of its name and itsauthor. This means that Person
must be serialized before Book
.To define this dependency, we add one extra line:Person
objects are serialized beforeany Book
objects. In turn, any object referencing Book
will beserialized after both Person
and Book
have been serialized.