Django Serialize Dict Object Has No Attribute Meta
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).
Serializers are used to serialize the django models only. To serialize simple python data use the built-in json module: import json return. Def listado_libros(request): cons=Libros.objects.values('nombre','autores_libros__nombre').
См.также
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, serializing data is a very simple operation:
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):
Примечание
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.
Примечание
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. Just call the serializer on the object (or objects) that you want toserialize, and the output will be a complete representation of the serializedobject.
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_dogsattribute. 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 also a fairly simple operation:
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 simple 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.
Примечание
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. Of course, if youtrust your data source you could just save the object 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 ignorenonexistentargument 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. |
yaml | Serializes to YAML (YAML Ain’t a Markup Language). Thisserializer is only available if PyYAML is installed. |
XML¶
The basic XML serialization format is quite simple:
The whole collection of objects that is either serialized or de-serialized isrepresented by a <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.
Each field of the object is serialized as a <field>-element sporting thefields “type” and “name”. The text content of the element represents the valuethat should be stored.
Foreign keys and other relational fields are treated a little bit differently:
In this example we specify that the auth.Permission object with the PK 27 hasa foreign key to the contenttypes.ContentType instance with the PK 9.
ManyToMany-relations are exported for the model that binds them. For instance,the auth.User model has such a relation to the auth.Permission model:
This example links the given user with the permission models with PKs 46 and 47.
JSON¶
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 just 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.
Date and datetime related types are treated in a special way by the JSONserializer to make the format compatible with ECMA-262.
Be aware that not all Django output can be passed unmodified to json.In particular, lazy translation objects need aspecial encoder written for them. Something like this will work:
Also note that GeoDjango provides a customized GeoJSON serializer.
YAML¶
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 just represented by the PK or sequence of PKs.
![Attribute Attribute](https://www.formget.com/wp-content/uploads/2014/07/Content-Serialize.png)
Natural keys¶
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 referencingContentType. 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.
Предупреждение
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 IntegrityError.
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.
Deserialization of natural keys¶
Consider the following two models:
Ordinarily, serialized data for Book would use an integer to refer tothe author. For example, in JSON, a Book might be serialized as:
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 get_by_natural_key() method. In the caseof a Person, a good natural key might be the pair of first and lastname:
Now books can use that natural key to refer to Person objects:
When you try to load this serialized data, Django will use theget_by_natural_key() method to resolve ['Douglas','Adams']into the primary key of an actual Person object.
Примечание
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, orunique_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.
Deserialization of objects with no primary key will always check whether themodel’s manager has a get_by_natural_key() method and if so, use it topopulate the deserialized object’s primary 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:
That method should always return a natural key tuple – in thisexample, (firstname,lastname). Then, when you callserializers.serialize(), you provide use_natural_foreign_keys=Trueor use_natural_primary_keys=True arguments:
When 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.
When 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:
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 dumpdata to generate serialized data, use the--natural-foreign and --natural-primary commandline flags to generate natural keys.
Примечание
You don’t need to define both 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.
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 get_by_natural_key() method.
Изменено в Django 1.7:Previously there was only a use_natural_keys argument forserializers.serialize() and the -n or –natural command line flags.These have been deprecated in favor of the use_natural_foreign_keys anduse_natural_primary_keys arguments and the corresponding--natural-foreign and --natural-primary optionsfor dumpdata.
The original argument and command line flags remain for backwardscompatibility and map to the new use_natural_foreign_keys argument and–natural-foreign command line flag. Skyrim pc activation code generator. They’ll be removed in Django 1.9.
Dependencies during serialization¶
Since natural keys rely on database lookups to resolve references, itis important that the data exists before it is referenced. You can’t makea “forward reference” with natural keys – the data you’re referencingmust exist before you include a natural key reference to that data.
To accommodate this limitation, calls to dumpdata that usethe --natural-foreign option will serialize any model with anatural_key() method before serializing standard primary key objects.
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 yournatural_key() methods. You do this by setting a dependenciesattribute on the natural_key() method itself.
For example, let’s add a natural key to the Book model from theexample above:
The natural key for a 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:
Dict Has No Attribute Iteritems
This definition ensures that all Person objects are serialized beforeany Book objects. In turn, any object referencing Book will beserialized after both Person and Book have been serialized.
I have this old site that was originally pre magic and got ported up 0.96where it still is and now have to make some alterations, this is a clone
site to do something different but the same BUT on getting to the
subsubcategory level (sorry my naming conventions back then really sucked) I
am getting, which is weird because the code is the same as the original site
that is working down to subsub level.. UH?
'dict' object has no attribute 'META'
Exception Location: /var/www/django/eco/django/core/context_processors.py
in debug, line 34
Traceback
Traceback Switch to copy-and-paste view
/var/www/django/eco/django/core/handlers/base.py in get_response
response = callback(request, *callback_args, **callback_kwargs) ..
▶ Local vars
/var/www/django/project/kitchens_bathrooms/views.py in subsub_cat
return render_to_response('kitchens_bathrooms/subsub.html',
RequestContext({'products':products,'banner':current_subsub_cat.get_banner(),
'resource': current_subsub_cat.get_resource(), 'sub_cats': master_sub_cats,
'sub_cat':current_sub_cat,'masters':masters,'master':current_master,'subsub_cats':master_subsub_cats,
'subsub_cat':current_subsub_cat,'urlswitch':
urlswitch,'brand_link':brand_link, 'brand_id':brand_id})) ..
▶ Local vars
/var/www/django/eco/django/template/context.py in __init__
self.update(processor(request)) ..
▶ Local vars
/var/www/django/eco/django/core/context_processors.py in debug
if settings.DEBUG and request.META.get('REMOTE_ADDR') in
settings.INTERNAL_IPS: ..
▶ Local vars
There is no GET or POST data
HTTP_REFERER
'http://domain/kitchens_bathrooms/water-saving-taps/water-saving-basin-taps/'
PATH_INFO
'/kitchens_bathrooms/water-saving-taps/water-saving-basin-taps/mono-basin-taps/'
Anyone have any ideas please because I am just going round in ever
decreasing circles??
Yeah I know port it to latest version and sort out the naming and also dont
use slug to navigate the urls but.... you all know how it is