Seriando objetos do Django

O framework de seriação do Django fornece um mecanismo para “traduzir” objetos do Django em outros formatos. Usualmente estes outros formatos serão baseados em texto e usados para enviar objetos do Django por um fio, mas é possível para um seriador manipular qualquer formato (baseado em texto ou não).

See also

Se você apenas quiser obter alguns dados de suas tabelas na forma serializada, você pode usar o comando dumbdata.

Serializando dados

No nível mais alto, seriar dados é uma operação muito simples:

from django.core import serializers
data = serializers.serialize("xml", SomeModel.objects.all())

Os argumentos para a função serialize são o formato para o qual os dados serão seriados (veja Formatos de seriação) e um QuerySet para seriar. (Na verdade, o segundo argumento pode ser qualquer iterador que fornece objetos Django, mas quase sempre será um QuerySet).

Você pode usar também um objeto seriador diretamente:

XMLSerializer = serializers.get_serializer("xml")
xml_serializer = XMLSerializer()
xml_serializer.serialize(queryset)
data = xml_serializer.getvalue()

Este é usuál se você quiser seriar dados diretamente para um objeto arquivo (que inclua um HttpResponse):

out = open("file.xml", "w")
xml_serializer.serialize(SomeModel.objects.all(), stream=out)

Subconjunto de campos

Se você somente quiser um subconjunto de campos para seriar, você pode especificar um argumento fields para o seriador:

from django.core import serializers
data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))

Neste exemplo, somente os atributos name e size de cada model serão seriados.

Note

Dependendo do seu modelo, você pode descobrir que não é possível desseriar um modelo que teve apenas um subconjunto de seus campos seriados. Se um objeto seriado não especificar todos os campos que são requeridos pelo mode, o desseriador não será capaz de salvar instâncias desseriadas.

Models herdados

Se você tem um model que é definido usando uma classe abstrata de base, você não terá de fazer nada especial para seriar este model. Somente chamar o seriador sobre o objeto (ou objetos) que você deseja seriar, e a saída será uma representação completa do objeto seriado.

Porém, se você tem um model que usa herança de multi-tabelas, você também precisa seriar todos as classes que dão base ao model. Isto porque somente os campos que são localmente definidos no model serão seriados. Por exemplo, considere os seguintes models:

class Place(models.Model):
    name = models.CharField(max_length=50)

class Restaurant(Place):
    serves_hot_dogs = models.BooleanField()

Se você somente seriar o model Restaurant:

data = serializers.serialize('xml', Restaurant.objects.all())

os campos na saída seriada conterão somente atributos serves_hot_dogs. O atributo name da classe de base será ignorado.

Afim de permitir uma seriação completa para sua instância Restaurant, você precisará seriar o model Place também:

all_objects = list(Restaurant.objects.all()) + list(Place.objects.all())
data = serializers.serialize('xml', all_objects)

Desseriando dados

Desseriamento de dados é também um operação bastante simples:

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

Como você pode ver, a função deserialize recebe o mesmo argumento de formato que o serialize, uma string ou stream de dados, e retorna um iterador.

Entretanto, aqui fica um pouco complicado. Os objetos retornado pelo iterador do deserialize não são objetos simples do Django. Em vez disso, eles são instâncias especiais DeserializedObject que envolvem o objeto criado -- mas não salvo -- e toda relação de dados.

Chamando DeserializedObject.save() salva o objeto no banco de dados.

Isso garante que a desseriação é uma operação não destrutiva mesmo se o dado na sua representação não bata com a que estiver agora no seu banco de dados. Normalmente, trabalhar com estas instâncias de DeserializedObject parece algo como:

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

Em outras palavras, o uso normal é examinar os objetos desseriados para ter certeza de que eles estão "adequados" a serem salvos antes de salvá-los. Logicamente, se você confiar na fonte de dados, poderá apenas salvar os objetos e seguir adiante.

O objeto Django em si pode ser inspecionado como deserialized_object.object.

Formatos de seriação

O Django suporta vários formatos de seriação, alguns que obrigam você instalar módulos de terceiros do Python:

Identificador Informações
xml Serializa para e do dialeto simples de XML.
json Serializa para e do JSON (usando uma versão do simplejson empacotada com o Django).
python Traduz para e dos objetos "simples" do Python (listas, dicionários, strings, etc.). Nem tudo dele é realmente útil, mas é usado como base para outros seriadores.
yaml Serializa para YAML (YAML não é uma linguagem de marcação). Este seriador é somente disponível se o PyYAML estiver instalado.

Notas para formatos de seriação específicos

json

Se você esta usando dados UTF-8 (ou qualquer outra codificação não-ASCII) com o seriador JSON, você passar ensure_ascii=False como parâmetro para a chamada serialize(). Por outro lado, a saída não pode será codificada corretamente.

Por exemplo:

json_serializer = serializers.get_serializer("json")()
json_serializer.serialize(queryset, ensure_ascii=False, stream=response)

O código do Django inclui o módulo simplejson. However, if you're using Python 2.6 or later (which includes a builtin version of the module), Django will use the builtin json module automatically. If you have a system installed version that includes the C-based speedup extension, or your system version is more recent than the version shipped with Django (currently, 2.0.7), the system version will be used instead of the version included with Django.

Tenha cuidado que se você estiver seriando usando este módulo diretamente, nem todas as saídas do Django podem ser passadas sem modificação para o simplejson. Em particular, objetos de tradução tardios precisam de um codificador especial escritos para eles. Algo como isto funcionará:

from django.utils.functional import Promise
from django.utils.encoding import force_unicode

class LazyEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Promise):
            return force_unicode(obj)
        return super(LazyEncoder, self).default(obj)

Natural keys

Novo no Django 1.2: Please, see the release notes

The default serialization strategy for foreign keys and many-to-many relations is to serialize the value of the primary key(s) of the objects in the relation. This strategy works well for most types of object, but it can cause difficulty in some circumstances.

Consider the case of a list of objects that have foreign key on ContentType. If you're going to serialize an object that refers to a content type, you need to have a way to refer to that content type. Content Types are automatically created by Django as part of the database synchronization process, so you don't need to include content types in a fixture or other serialized data. As a result, the primary key of any given content type isn't easy to predict - it will depend on how and when syncdb was executed to create the content types.

There is also the matter of convenience. An integer id isn't always the most convenient way to refer to an object; sometimes, a more natural reference would be helpful.

It is for these reasons that Django provides natural keys. A natural key is a tuple of values that can be used to uniquely identify an object instance without using the primary key value.

Deserialization of natural keys

Consider the following two models:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    birthdate = models.DateField()

    class Meta:
        unique_together = (('first_name', 'last_name'),)

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.ForeignKey(Person)

Ordinarily, serialized data for Book would use an integer to refer to the author. For example, in JSON, a Book might be serialized as:

...
{
    "pk": 1,
    "model": "store.book",
    "fields": {
        "name": "Mostly Harmless",
        "author": 42
    }
}
...

This isn't a particularly natural way to refer to an author. It requires that you know the primary key value for the author; it also requires that this primary key value is stable and predictable.

However, if we add natural key handling to Person, the fixture becomes much more humane. To add natural key handling, you define a default Manager for Person with a get_by_natural_key() method. In the case of a Person, a good natural key might be the pair of first and last name:

from django.db import models

class PersonManager(models.Manager):
    def get_by_natural_key(self, first_name, last_name):
        return self.get(first_name=first_name, last_name=last_name)

class Person(models.Model):
    objects = PersonManager()

    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    birthdate = models.DateField()

    class Meta:
        unique_together = (('first_name', 'last_name'),)

Now books can use that natural key to refer to Person objects:

...
{
    "pk": 1,
    "model": "store.book",
    "fields": {
        "name": "Mostly Harmless",
        "author": ["Douglas", "Adams"]
    }
}
...

When you try to load this serialized data, Django will use the get_by_natural_key() method to resolve ["Douglas", "Adams"] into the primary key of an actual Person object.

Note

Whatever fields you use for a natural key must be able to uniquely identify an object. This will usually mean that your model will have a uniqueness clause (either unique=True on a single field, or unique_together over multiple fields) for the field or fields in your natural key. However, uniqueness doesn't need to be enforced at the database level. If you are certain that a set of fields will be effectively unique, you can still use those fields as a natural key.

Serialization of natural keys

So how do you get Django to emit a natural key when serializing an object? Firstly, you need to add another method -- this time to the model itself:

class Person(models.Model):
    objects = PersonManager()

    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    birthdate = models.DateField()

    def natural_key(self):
        return (self.first_name, self.last_name)

    class Meta:
        unique_together = (('first_name', 'last_name'),)

That method should always return a natural key tuple -- in this example, (first name, last name). Then, when you call serializers.serialize(), you provide a use_natural_keys=True argument:

>>> serializers.serialize('json', [book1, book2], indent=2, use_natural_keys=True)

When use_natural_keys=True is specified, Django will use the natural_key() method to serialize any reference to objects of the type that defines the method.

If you are using dumpdata to generate serialized data, you use the --natural command line flag to generate natural keys.

Note

You don't need to define both natural_key() and get_by_natural_key(). If you don't want Django to output natural keys during serialization, but you want to retain the ability to load natural keys, then you can opt to not implement the natural_key() method.

Conversely, if (for some strange reason) you want Django to output natural keys during serialization, but not be able to load those key values, just don't define the get_by_natural_key() method.

Dependencies during serialization

Since natural keys rely on database lookups to resolve references, it is important that data exists before it is referenced. You can't make a forward reference with natural keys - the data you are referencing must exist before you include a natural key reference to that data.

To accommodate this limitation, calls to dumpdata that use the --natural option will serialize any model with a natural_key() method before it serializes normal key objects.

However, this may not always be enough. If your natural key refers to another object (by using a foreign key or natural key to another object as part of a natural key), then you need to be able to ensure that the objects on which a natural key depends occur in the serialized data before the natural key requires them.

To control this ordering, you can define dependencies on your natural_key() methods. You do this by setting a dependencies attribute on the natural_key() method itself.

For example, consider the Permission model in contrib.auth. The following is a simplified version of the Permission model:

class Permission(models.Model):
    name = models.CharField(max_length=50)
    content_type = models.ForeignKey(ContentType)
    codename = models.CharField(max_length=100)
    # ...
    def natural_key(self):
        return (self.codename,) + self.content_type.natural_key()

The natural key for a Permission is a combination of the codename for the Permission, and the ContentType to which the Permission applies. This means that ContentType must be serialized before Permission. To define this dependency, we add one extra line:

class Permission(models.Model):
    # ...
    def natural_key(self):
        return (self.codename,) + self.content_type.natural_key()
    natural_key.dependencies = ['contenttypes.contenttype']

This definition ensures that ContentType models are serialized before Permission models. In turn, any object referencing Permission will be serialized after both ContentType and Permission.