Django's serialization framework provides a mechanism for 'translating' Djangomodels into other formats. Usually these other formats will be text-based andused for sending Django data over a wire, but it's possible for aserializer to handle any format (text-based or not).
- Django Serialize Dict Object Has No Attribute Metal
- Django Serialize Dict Object Has No Attribute Metales
- Object Has No Attribute Python
In order to lift the barrier, you need the 3 Stanzas of Kagrenac. Django serialize dict object has no attribute meta. 22.1 First Stanza of Kagrenac:-High Hrothgar.Front door entry, then go all the way down the second hallway from the left. 22.2 Second Stanza of Kagrenac:- Bronzewater Cave 22.3 Third Stanza of Kagrenac:- Calcelmo's Dwemer museum in Markarth, the one before the balcony where.
- All groups and messages.
- Python answers related to 'queryset object has no attribute meta in django' AttributeError: 'dict' object has no attribute 'iteritems' AttributeError: module 'django.contrib.auth.views' has no attribute 'login' AttributeError: 'Database' object has no attribute 'remove' AttributeError: type object 'User' has no attribute 'query'.
- 回答1: Django core serializers can only serialize a queryset. But values doesn't return queryset, rather a ValuesQuerySet object. You can specifiy the fields you wish to use in values in the serialize method as follows.
See also
If you just want to get some data from your tables into a serializedform, you could use the dumpdata
management command.
Serializing data¶
At the highest level, you can serialize data like this:
The arguments to the 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)¶
You can also use a serializer object directly:
This is useful if you want to serialize data directly to a file-like object(which includes an HttpResponse
):
Note
Calling get_serializer()
with an unknownformat will raise adjango.core.serializers.SerializerDoesNotExist
exception.
Subset of fields¶
If you only want a subset of fields to be serialized, you canspecify a fields
argument to the serializer:
In this example, only the 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.
Note
Depending on your model, you may find that it is not possible todeserialize a model that only serializes a subset of its fields. If aserialized object doesn't specify all the fields that are required by amodel, the deserializer will not be able to save deserialized instances.
Inherited models¶
If you have a model that is defined using an abstract base class, you don't have to do anything special to serializethat model. Call the serializer on the object (or objects) that you want toserialize, and the output will be a complete representation of the serializedobject.
Django Serialize Dict Object Has No Attribute Metal
However, if you have a model that uses multi-table inheritance, you also need to serialize all of the base classesfor the model. This is because only the fields that are locally defined on themodel will be serialized. For example, consider the following models:
If you only serialize the Restaurant model:
the fields on the serialized output will only contain the serves_hot_dogs
attribute. The name
attribute of the base class will be ignored.
In order to fully serialize your Restaurant
instances, you will need toserialize the Place
models as well:
Deserializing data¶
Deserializing data is very similar to serializing it:
As you can see, the deserialize
function takes the same format argument asserialize
, a string or stream of data, and returns an iterator.
However, here it gets slightly complicated. The objects returned by thedeserialize
iterator aren't regular Django objects. Instead, they arespecial DeserializedObject
instances that wrap a created – but unsaved –object and any associated relationship data.
Calling DeserializedObject.save()
saves the object to the database.
Note
If the pk
attribute in the serialized data doesn't exist or isnull, a new instance will be saved to the database.
This ensures that deserializing is a non-destructive operation even if thedata in your serialized representation doesn't match what's currently in thedatabase. Usually, working with these DeserializedObject
instances lookssomething like:
In other words, the usual use is to examine the deserialized objects to makesure that they are 'appropriate' for saving before doing so. If you trust yourdata source you can instead save the object directly and move on.
The Django object itself can be inspected as 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
:
Serialization formats¶
Django supports a number of serialization formats, some of which require youto install third-party Python modules:
Identifier | Information |
---|---|
xml | Serializes to and from a simple XML dialect. |
json | Serializes to and from JSON. |
jsonl | Serializes to and from JSONL. |
yaml | Serializes to YAML (YAML Ain't a Markup Language). Thisserializer is only available if PyYAML is installed. |
XML¶
The basic XML serialization format looks like this:
The whole collection of objects that is either serialized or deserialized isrepresented by a Each field of the object is serialized as a Foreign keys and other relational fields are treated a little bit differently: In this example we specify that the ManyToMany-relations are exported for the model that binds them. For instance,the This example links the given user with the permission models with PKs 46 and 47. Control characters If the content to be serialized contains control characters that are notaccepted in the XML 1.0 standard, the serialization will fail with a When staying with the same example data as before it would be serialized asJSON in the following way: The formatting here is a bit simpler than with XML. The whole collectionis just represented as an array and the objects are represented by JSON objectswith three properties: 'pk', 'model' and 'fields'. 'fields' is again an objectcontaining each field's name and value as property and property-valuerespectively. Foreign keys have the PK of the linked object as property value.ManyToMany-relations are serialized for the model that defines them and arerepresented as a list of PKs. Be aware that not all Django output can be passed unmodified to You can then pass Also note that GeoDjango provides a customized GeoJSON serializer. Amigaos 3.9 adf download. Tekken 5 iso for ppsspp. All data is now dumped with Unicode. If you need the previous behavior,pass The JSON serializer uses JSONL stands for JSON Lines. With this format, objects are separated by newlines, and each line contains a valid JSON object. JSONL serialized data lookslike this: JSONL can be useful for populating large databases, since the data can beprocessed line by line, rather than being loaded into memory all at once. YAML serialization looks quite similar to JSON. The object list is serializedas a sequence mappings with the keys 'pk', 'model' and 'fields'. Each field isagain a mapping with the key being name of the field and the value the value: Referential fields are again represented by the PK or sequence of PKs. All data is now dumped with Unicode. If you need the previous behavior,pass The default serialization strategy for foreign keys and many-to-many relationsis to serialize the value of the primary key(s) of the objects in the relation.This strategy works well for most objects, but it can cause difficulty in somecircumstances. Consider the case of a list of objects that have a foreign key referencing Warning You should never include automatically generated objects in a fixture orother serialized data. By chance, the primary keys in the fixturemay match those in the database and loading the fixture willhave no effect. In the more likely case that they don't match, the fixtureloading will fail with an There is also the matter of convenience. An integer id isn't alwaysthe most convenient way to refer to an object; sometimes, amore natural reference would be helpful. It is for these reasons that Django provides natural keys. A naturalkey is a tuple of values that can be used to uniquely identify anobject instance without using the primary key value. Consider the following two models: Ordinarily, serialized data for This isn't a particularly natural way to refer to an author. Itrequires that you know the primary key value for the author; it alsorequires that this primary key value is stable and predictable. However, if we add natural key handling to Person, the fixture becomesmuch more humane. To add natural key handling, you define a defaultManager for Person with a Now books can use that natural key to refer to When you try to load this serialized data, Django will use the Note Whatever fields you use for a natural key must be able to uniquelyidentify an object. This will usually mean that your model willhave a uniqueness clause (either unique=True on a single field, or Deserialization of objects with no primary key will always check whether themodel's manager has a 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: That method should always return a natural key tuple – in thisexample, When When This can be useful when you need to load serialized data into an existingdatabase and you cannot guarantee that the serialized primary key value is notalready in use, and do not need to ensure that deserialized objects retain thesame primary keys. If you are using Note You don't need to define both Conversely, if (for some strange reason) you want Django to outputnatural keys during serialization, but not be able to load thosekey values, just don't define the Sometimes when you use natural foreign keys you'll need to deserialize data wherean object has a foreign key referencing another object that hasn't yet beendeserialized. This is called a 'forward reference'.-tag which contains multiple
-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.
-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¶
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:ensure_ascii=True
to the serializers.serialize()
function.DjangoJSONEncoder
¶django.core.serializers.json.
DjangoJSONEncoder
¶Django Serialize Dict Object Has No Attribute Metales
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
JSONL¶
YAML¶
allow_unicode=False
to the serializers.serialize()
function.Natural keys¶
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
.Deserialization of natural keys¶
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.Serialization of natural keys¶
(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.Natural keys and forward references¶
django.core.serializers.
get_serializer
(format)¶
You can also use a serializer object directly:
This is useful if you want to serialize data directly to a file-like object(which includes an HttpResponse
):
Note
Calling get_serializer()
with an unknownformat will raise adjango.core.serializers.SerializerDoesNotExist
exception.
Subset of fields¶
If you only want a subset of fields to be serialized, you canspecify a fields
argument to the serializer:
In this example, only the 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.
Note
Depending on your model, you may find that it is not possible todeserialize a model that only serializes a subset of its fields. If aserialized object doesn't specify all the fields that are required by amodel, the deserializer will not be able to save deserialized instances.
Inherited models¶
If you have a model that is defined using an abstract base class, you don't have to do anything special to serializethat model. Call the serializer on the object (or objects) that you want toserialize, and the output will be a complete representation of the serializedobject.
Django Serialize Dict Object Has No Attribute Metal
However, if you have a model that uses multi-table inheritance, you also need to serialize all of the base classesfor the model. This is because only the fields that are locally defined on themodel will be serialized. For example, consider the following models:
If you only serialize the Restaurant model:
the fields on the serialized output will only contain the serves_hot_dogs
attribute. The name
attribute of the base class will be ignored.
In order to fully serialize your Restaurant
instances, you will need toserialize the Place
models as well:
Deserializing data¶
Deserializing data is very similar to serializing it:
As you can see, the deserialize
function takes the same format argument asserialize
, a string or stream of data, and returns an iterator.
However, here it gets slightly complicated. The objects returned by thedeserialize
iterator aren't regular Django objects. Instead, they arespecial DeserializedObject
instances that wrap a created – but unsaved –object and any associated relationship data.
Calling DeserializedObject.save()
saves the object to the database.
Note
If the pk
attribute in the serialized data doesn't exist or isnull, a new instance will be saved to the database.
This ensures that deserializing is a non-destructive operation even if thedata in your serialized representation doesn't match what's currently in thedatabase. Usually, working with these DeserializedObject
instances lookssomething like:
In other words, the usual use is to examine the deserialized objects to makesure that they are 'appropriate' for saving before doing so. If you trust yourdata source you can instead save the object directly and move on.
The Django object itself can be inspected as 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
:
Serialization formats¶
Django supports a number of serialization formats, some of which require youto install third-party Python modules:
Identifier | Information |
---|---|
xml | Serializes to and from a simple XML dialect. |
json | Serializes to and from JSON. |
jsonl | Serializes to and from JSONL. |
yaml | Serializes to YAML (YAML Ain't a Markup Language). Thisserializer is only available if PyYAML is installed. |
XML¶
The basic XML serialization format looks like this:
The whole collection of objects that is either serialized or deserialized isrepresented by a Each field of the object is serialized as a Foreign keys and other relational fields are treated a little bit differently: In this example we specify that the ManyToMany-relations are exported for the model that binds them. For instance,the This example links the given user with the permission models with PKs 46 and 47. Control characters If the content to be serialized contains control characters that are notaccepted in the XML 1.0 standard, the serialization will fail with a When staying with the same example data as before it would be serialized asJSON in the following way: The formatting here is a bit simpler than with XML. The whole collectionis just represented as an array and the objects are represented by JSON objectswith three properties: 'pk', 'model' and 'fields'. 'fields' is again an objectcontaining each field's name and value as property and property-valuerespectively. Foreign keys have the PK of the linked object as property value.ManyToMany-relations are serialized for the model that defines them and arerepresented as a list of PKs. Be aware that not all Django output can be passed unmodified to You can then pass Also note that GeoDjango provides a customized GeoJSON serializer. Amigaos 3.9 adf download. Tekken 5 iso for ppsspp. All data is now dumped with Unicode. If you need the previous behavior,pass The JSON serializer uses JSONL stands for JSON Lines. With this format, objects are separated by newlines, and each line contains a valid JSON object. JSONL serialized data lookslike this: JSONL can be useful for populating large databases, since the data can beprocessed line by line, rather than being loaded into memory all at once. YAML serialization looks quite similar to JSON. The object list is serializedas a sequence mappings with the keys 'pk', 'model' and 'fields'. Each field isagain a mapping with the key being name of the field and the value the value: Referential fields are again represented by the PK or sequence of PKs. All data is now dumped with Unicode. If you need the previous behavior,pass The default serialization strategy for foreign keys and many-to-many relationsis to serialize the value of the primary key(s) of the objects in the relation.This strategy works well for most objects, but it can cause difficulty in somecircumstances. Consider the case of a list of objects that have a foreign key referencing Warning You should never include automatically generated objects in a fixture orother serialized data. By chance, the primary keys in the fixturemay match those in the database and loading the fixture willhave no effect. In the more likely case that they don't match, the fixtureloading will fail with an There is also the matter of convenience. An integer id isn't alwaysthe most convenient way to refer to an object; sometimes, amore natural reference would be helpful. It is for these reasons that Django provides natural keys. A naturalkey is a tuple of values that can be used to uniquely identify anobject instance without using the primary key value. Consider the following two models: Ordinarily, serialized data for This isn't a particularly natural way to refer to an author. Itrequires that you know the primary key value for the author; it alsorequires that this primary key value is stable and predictable. However, if we add natural key handling to Person, the fixture becomesmuch more humane. To add natural key handling, you define a defaultManager for Person with a Now books can use that natural key to refer to When you try to load this serialized data, Django will use the Note Whatever fields you use for a natural key must be able to uniquelyidentify an object. This will usually mean that your model willhave a uniqueness clause (either unique=True on a single field, or Deserialization of objects with no primary key will always check whether themodel's manager has a 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: That method should always return a natural key tuple – in thisexample, When When This can be useful when you need to load serialized data into an existingdatabase and you cannot guarantee that the serialized primary key value is notalready in use, and do not need to ensure that deserialized objects retain thesame primary keys. If you are using Note You don't need to define both Conversely, if (for some strange reason) you want Django to outputnatural keys during serialization, but not be able to load thosekey values, just don't define the Sometimes when you use natural foreign keys you'll need to deserialize data wherean object has a foreign key referencing another object that hasn't yet beendeserialized. This is called a 'forward reference'. For instance, suppose you have the following objects in your fixture: In order to handle this situation, you need to pass Typical usage looks like this: For this to work, the It's often possible to avoid explicitly having to handle forward references bytaking care with the ordering of objects within a fixture. To help with this, calls to However, this may not always be enough. If your natural key refers toanother object (by using a foreign key or natural key to another objectas part of a natural key), then you need to be able to ensure thatthe objects on which a natural key depends occur in the serialized databefore the natural key requires them. To control this ordering, you can define dependencies on your For example, let's add a natural key to the The natural key for a This definition ensures that all -tag which contains multiple
-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.
-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¶
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:ensure_ascii=True
to the serializers.serialize()
function.DjangoJSONEncoder
¶django.core.serializers.json.
DjangoJSONEncoder
¶Django Serialize Dict Object Has No Attribute Metales
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
JSONL¶
YAML¶
allow_unicode=False
to the serializers.serialize()
function.Natural keys¶
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
.Deserialization of natural keys¶
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.Serialization of natural keys¶
(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.Natural keys and forward references¶
Object Has No Attribute Python
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
.Dependencies during serialization¶
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.