{"payload":{"allShortcutsEnabled":false,"fileTree":{"docs":{"items":[{"name":"man","path":"docs/man","contentType":"directory"},{"name":"Makefile","path":"docs/Makefile","contentType":"file"},{"name":"add_ons.txt","path":"docs/add_ons.txt","contentType":"file"},{"name":"admin_css.txt","path":"docs/admin_css.txt","contentType":"file"},{"name":"apache_auth.txt","path":"docs/apache_auth.txt","contentType":"file"},{"name":"api_stability.txt","path":"docs/api_stability.txt","contentType":"file"},{"name":"authentication.txt","path":"docs/authentication.txt","contentType":"file"},{"name":"cache.txt","path":"docs/cache.txt","contentType":"file"},{"name":"conf.py","path":"docs/conf.py","contentType":"file"},{"name":"contenttypes.txt","path":"docs/contenttypes.txt","contentType":"file"},{"name":"contributing.txt","path":"docs/contributing.txt","contentType":"file"},{"name":"csrf.txt","path":"docs/csrf.txt","contentType":"file"},{"name":"custom_model_fields.txt","path":"docs/custom_model_fields.txt","contentType":"file"},{"name":"databases.txt","path":"docs/databases.txt","contentType":"file"},{"name":"databrowse.txt","path":"docs/databrowse.txt","contentType":"file"},{"name":"db-api.txt","path":"docs/db-api.txt","contentType":"file"},{"name":"design_philosophies.txt","path":"docs/design_philosophies.txt","contentType":"file"},{"name":"distributions.txt","path":"docs/distributions.txt","contentType":"file"},{"name":"django-admin.txt","path":"docs/django-admin.txt","contentType":"file"},{"name":"documentation.txt","path":"docs/documentation.txt","contentType":"file"},{"name":"email.txt","path":"docs/email.txt","contentType":"file"},{"name":"faq.txt","path":"docs/faq.txt","contentType":"file"},{"name":"fastcgi.txt","path":"docs/fastcgi.txt","contentType":"file"},{"name":"flatpages.txt","path":"docs/flatpages.txt","contentType":"file"},{"name":"form_for_model.txt","path":"docs/form_for_model.txt","contentType":"file"},{"name":"form_preview.txt","path":"docs/form_preview.txt","contentType":"file"},{"name":"form_wizard.txt","path":"docs/form_wizard.txt","contentType":"file"},{"name":"forms.txt","path":"docs/forms.txt","contentType":"file"},{"name":"generic_views.txt","path":"docs/generic_views.txt","contentType":"file"},{"name":"i18n.txt","path":"docs/i18n.txt","contentType":"file"},{"name":"index.txt","path":"docs/index.txt","contentType":"file"},{"name":"install.txt","path":"docs/install.txt","contentType":"file"},{"name":"legacy_databases.txt","path":"docs/legacy_databases.txt","contentType":"file"},{"name":"localflavor.txt","path":"docs/localflavor.txt","contentType":"file"},{"name":"middleware.txt","path":"docs/middleware.txt","contentType":"file"},{"name":"model-api.txt","path":"docs/model-api.txt","contentType":"file"},{"name":"modelforms.txt","path":"docs/modelforms.txt","contentType":"file"},{"name":"modpython.txt","path":"docs/modpython.txt","contentType":"file"},{"name":"newforms.txt","path":"docs/newforms.txt","contentType":"file"},{"name":"outputting_csv.txt","path":"docs/outputting_csv.txt","contentType":"file"},{"name":"outputting_pdf.txt","path":"docs/outputting_pdf.txt","contentType":"file"},{"name":"overview.txt","path":"docs/overview.txt","contentType":"file"},{"name":"pagination.txt","path":"docs/pagination.txt","contentType":"file"},{"name":"redirects.txt","path":"docs/redirects.txt","contentType":"file"},{"name":"release_notes_0.95.txt","path":"docs/release_notes_0.95.txt","contentType":"file"},{"name":"release_notes_0.96.txt","path":"docs/release_notes_0.96.txt","contentType":"file"},{"name":"request_response.txt","path":"docs/request_response.txt","contentType":"file"},{"name":"serialization.txt","path":"docs/serialization.txt","contentType":"file"},{"name":"sessions.txt","path":"docs/sessions.txt","contentType":"file"},{"name":"settings.txt","path":"docs/settings.txt","contentType":"file"},{"name":"shortcuts.txt","path":"docs/shortcuts.txt","contentType":"file"},{"name":"sitemaps.txt","path":"docs/sitemaps.txt","contentType":"file"},{"name":"sites.txt","path":"docs/sites.txt","contentType":"file"},{"name":"static_files.txt","path":"docs/static_files.txt","contentType":"file"},{"name":"syndication_feeds.txt","path":"docs/syndication_feeds.txt","contentType":"file"},{"name":"templates.txt","path":"docs/templates.txt","contentType":"file"},{"name":"templates_python.txt","path":"docs/templates_python.txt","contentType":"file"},{"name":"testing.txt","path":"docs/testing.txt","contentType":"file"},{"name":"transactions.txt","path":"docs/transactions.txt","contentType":"file"},{"name":"tutorial01.txt","path":"docs/tutorial01.txt","contentType":"file"},{"name":"tutorial02.txt","path":"docs/tutorial02.txt","contentType":"file"},{"name":"tutorial03.txt","path":"docs/tutorial03.txt","contentType":"file"},{"name":"tutorial04.txt","path":"docs/tutorial04.txt","contentType":"file"},{"name":"unicode.txt","path":"docs/unicode.txt","contentType":"file"},{"name":"url_dispatch.txt","path":"docs/url_dispatch.txt","contentType":"file"},{"name":"webdesign.txt","path":"docs/webdesign.txt","contentType":"file"}],"totalCount":66},"":{"items":[{"name":"django","path":"django","contentType":"directory"},{"name":"docs","path":"docs","contentType":"directory"},{"name":"examples","path":"examples","contentType":"directory"},{"name":"extras","path":"extras","contentType":"directory"},{"name":"scripts","path":"scripts","contentType":"directory"},{"name":"tests","path":"tests","contentType":"directory"},{"name":"AUTHORS","path":"AUTHORS","contentType":"file"},{"name":"INSTALL","path":"INSTALL","contentType":"file"},{"name":"LICENSE","path":"LICENSE","contentType":"file"},{"name":"MANIFEST.in","path":"MANIFEST.in","contentType":"file"},{"name":"README","path":"README","contentType":"file"},{"name":"setup.cfg","path":"setup.cfg","contentType":"file"},{"name":"setup.py","path":"setup.py","contentType":"file"}],"totalCount":13}},"fileTreeProcessingTime":10.768695,"foldersToFetch":[],"repo":{"id":4164482,"defaultBranch":"main","name":"django","ownerLogin":"django","currentUserCanPush":false,"isFork":false,"isEmpty":false,"createdAt":"2012-04-28T02:47:18.000Z","ownerAvatar":"https://avatars.githubusercontent.com/u/27804?v=4","public":true,"private":false,"isOrgOwned":true},"symbolsExpanded":false,"treeExpanded":true,"refInfo":{"name":"12716794dbcf2e1bf7a07bd18dfc0ae24be4e6f8","listCacheKey":"v0:1709542684.0","canEdit":false,"refType":"tree","currentOid":"12716794dbcf2e1bf7a07bd18dfc0ae24be4e6f8"},"path":"docs/serialization.txt","currentUser":null,"blob":{"rawLines":["==========================","Serializing Django objects","==========================","",".. note::",""," This API is currently under heavy development and may change --"," perhaps drastically -- in the future.",""," You have been warned.","","Django's serialization framework provides a mechanism for \"translating\" Django","objects into other formats. Usually these other formats will be text-based and","used for sending Django objects over a wire, but it's possible for a","serializer to handle any format (text-based or not).","","Serializing data","----------------","","At the highest level, serializing data is a very simple operation::",""," from django.core import serializers"," data = serializers.serialize(\"xml\", SomeModel.objects.all())","","The arguments to the ``serialize`` function are the format to serialize the","data to (see `Serialization formats`_) and a QuerySet_ to serialize.","(Actually, the second argument can be any iterator that yields Django objects,","but it'll almost always be a QuerySet).","",".. _QuerySet: ../db-api/#retrieving-objects","","You can also use a serializer object directly::",""," XMLSerializer = serializers.get_serializer(\"xml\")"," xml_serializer = XMLSerializer()"," xml_serializer.serialize(queryset)"," data = xml_serializer.getvalue()","","This is useful if you want to serialize data directly to a file-like object","(which includes a HTTPResponse_)::",""," out = open(\"file.xml\", \"w\")"," xml_serializer.serialize(SomeModel.objects.all(), stream=out)","",".. _HTTPResponse: ../request_response/#httpresponse-objects","","Subset of fields","~~~~~~~~~~~~~~~~","","If you only want a subset of fields to be serialized, you can","specify a ``fields`` argument to the serializer::",""," from django.core import serializers"," data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))","","In this example, only the ``name`` and ``size`` attributes of each model will","be serialized.","",".. note::",""," Depending on your model, you may find that it is not possible to deserialize"," a model that only serializes a subset of its fields. If a serialized object"," doesn't specify all the fields that are required by a model, 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 serialize that model. Just call the serializer","on the object (or objects) that you want to serialize, and the output will be","a complete representation of the serialized object.","","However, if you have a model that uses `multi-table inheritance`_, you also","need to serialize all of the base classes for the model. This is because only","the fields that are locally defined on the model will be serialized. For","example, consider the following models::","\t","\tclass Place(models.Model):","\t\tname = models.CharField(max_length=50)","\t\t","\tclass Restaurant(Place):","\t\tserves_hot_dogs = models.BooleanField()","\t\t","If you only serialize the Restaurant model::","","\tdata = serializers.serialize('xml', Restaurant.objects.all())","","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 to","serialize the Place models as well::","","\tall_objects = list(Restaurant.objects.all()) + list(Place.objects.all())","\tdata = serializers.serialize('xml', all_objects)","",".. _abstract base class: http://www.djangoproject.com/documentation/model-api/#abstract-base-classes",".. _multi-table inheritance: http://www.djangoproject.com/documentation/model-api/#multi-table-inheritance","","Deserializing data","------------------","","Deserializing data is also a fairly simple operation::",""," for obj in serializers.deserialize(\"xml\", data):"," do_something_with(obj)","","As you can see, the ``deserialize`` function takes the same format argument as","``serialize``, a string or stream of data, and returns an iterator.","","However, here it gets slightly complicated. The objects returned by the","``deserialize`` iterator *aren't* simple Django objects. Instead, they are","special ``DeserializedObject`` instances that wrap a created -- but unsaved --","object and any associated relationship data.","","Calling ``DeserializedObject.save()`` saves the object to the database.","","This ensures that deserializing is a non-destructive operation even if the","data in your serialized representation doesn't match what's currently in the","database. Usually, working with these ``DeserializedObject`` instances looks","something like::",""," for deserialized_object in serializers.deserialize(\"xml\", data):"," if object_should_be_saved(deserialized_object):"," deserialized_object.save()","","In other words, the usual use is to examine the deserialized objects to make","sure that they are \"appropriate\" for saving before doing so. Of course, if you trust your data source you could just save the object and move on.","","The Django object itself can be inspected as ``deserialized_object.object``.","","Serialization formats","---------------------","","Django \"ships\" with a few included serializers:",""," ========== =============================================================="," Identifier Information"," ========== =============================================================="," ``xml`` Serializes to and from a simple XML dialect.",""," ``json`` Serializes to and from JSON_ (using a version of simplejson_"," bundled with Django).",""," ``python`` Translates to and from \"simple\" Python objects (lists, dicts,"," strings, etc.). Not really all that useful on its own, but"," used as a base for other serializers.",""," ``yaml`` Serializes to YAML (YAML Ain't a Markup Language). This"," serializer is only available if PyYAML_ is installed."," ========== ==============================================================","",".. _json: http://json.org/",".. _simplejson: http://undefined.org/python/#simplejson",".. _PyYAML: http://www.pyyaml.org/","","Notes for specific serialization formats","----------------------------------------","","json","~~~~","","If you're using UTF-8 (or any other non-ASCII encoding) data with the JSON","serializer, you must pass ``ensure_ascii=False`` as a parameter to the","``serialize()`` call. Otherwise, the output won't be encoded correctly.","","For example::",""," json_serializer = serializers.get_serializer(\"json\")()"," json_serializer.serialize(queryset, ensure_ascii=False, stream=response)","","The Django source code includes the simplejson_ module. Be aware that if","you're serializing using that module directly, not all Django output can be","passed unmodified to simplejson. In particular, `lazy translation objects`_","need a `special encoder`_ written for them. Something like this will work::",""," 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 obj","",".. _lazy translation objects: ../i18n/#lazy-translation",".. _special encoder: http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html"],"stylingDirectives":[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]],"colorizedLines":null,"csv":null,"csvError":null,"dependabotInfo":{"showConfigurationBanner":false,"configFilePath":null,"networkDependabotPath":"/django/django/network/updates","dismissConfigurationNoticePath":"/settings/dismiss-notice/dependabot_configuration_notice","configurationNoticeDismissed":null},"displayName":"serialization.txt","displayUrl":"https://github.com/django/django/blob/12716794dbcf2e1bf7a07bd18dfc0ae24be4e6f8/docs/serialization.txt?raw=true","headerInfo":{"blobSize":"7.07 KB","deleteTooltip":"You must be signed in to make or propose changes","editTooltip":"You must be signed in to make or propose changes","ghDesktopPath":null,"isGitLfs":false,"onBranch":false,"shortPath":"2a3e703","siteNavLoginPath":"/login?return_to=https%3A%2F%2Fgithub.com%2Fdjango%2Fdjango%2Fblob%2F12716794dbcf2e1bf7a07bd18dfc0ae24be4e6f8%2Fdocs%2Fserialization.txt","isCSV":false,"isRichtext":false,"toc":null,"lineInfo":{"truncatedLoc":"188","truncatedSloc":"131"},"mode":"file"},"image":false,"isCodeownersFile":null,"isPlain":false,"isValidLegacyIssueTemplate":false,"issueTemplate":null,"discussionTemplate":null,"language":"Text","languageID":372,"large":false,"planSupportInfo":{"repoIsFork":null,"repoOwnedByCurrentUser":null,"requestFullPath":"/django/django/blob/12716794dbcf2e1bf7a07bd18dfc0ae24be4e6f8/docs/serialization.txt","showFreeOrgGatedFeatureMessage":null,"showPlanSupportBanner":null,"upgradeDataAttributes":null,"upgradePath":null},"publishBannersInfo":{"dismissActionNoticePath":"/settings/dismiss-notice/publish_action_from_dockerfile","releasePath":"/django/django/releases/new?marketplace=true","showPublishActionBanner":false},"rawBlobUrl":"https://github.com/django/django/raw/12716794dbcf2e1bf7a07bd18dfc0ae24be4e6f8/docs/serialization.txt","renderImageOrRaw":false,"richText":null,"renderedFileInfo":null,"shortPath":null,"symbolsEnabled":true,"tabSize":8,"topBannersInfo":{"overridingGlobalFundingFile":false,"globalPreferredFundingPath":null,"showInvalidCitationWarning":false,"citationHelpUrl":"https://docs.github.com/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-citation-files","actionsOnboardingTip":null},"truncated":false,"viewable":true,"workflowRedirectUrl":null,"symbols":{"timed_out":false,"not_analyzed":true,"symbols":[]}},"copilotInfo":null,"copilotAccessAllowed":false,"csrf_tokens":{"/django/django/branches":{"post":"SvkRwUZbFp42k2-eCoAHF26tjx1xeQBdgF5Qp9OjpzouwHMbDc8s4Ak06QT7H6NEOGi_1BioelbR1bNCD40fyA"},"/repos/preferences":{"post":"skitmmM7mBZO6xTEtKKDnxhJcvhX3B0XhaO0FFh-pamexZtVaPEB8dagFBLzxSINFbMLTMTnSCOcR_ezTcZAog"}}},"title":"django/docs/serialization.txt at 12716794dbcf2e1bf7a07bd18dfc0ae24be4e6f8 ยท django/django"}