Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability. The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a queryset with one object. If, on the other hand, what you need is a way to re-inflate the model instance somewhere else without touching the database or without using Django, then you have a little bit of work to do.</p> <p>Here's what I do:</p> <p>First, I use <a href="http://deron.meranda.us/python/demjson/" rel="noreferrer"><code>demjson</code></a> for the conversion. It happened to be what I found first, but it might not be the best. My implementation depends on one of its features, but there should be similar ways with other converters.</p> <p>Second, implement a <code>json_equivalent</code> method on all models that you might need serialized. This is a magic method for <code>demjson</code>, but it's probably something you're going to want to think about no matter what implementation you choose. The idea is that you return an object that is directly convertible to <code>json</code> (i.e. an array or dictionary). If you really want to do this automatically:</p> <pre><code>def json_equivalent(self): dictionary = {} for field in self._meta.get_all_field_names() dictionary[field] = self.__getattribute__(field) return dictionary </code></pre> <p>This will not be helpful to you unless you have a completely flat data structure (no <code>ForeignKeys</code>, only numbers and strings in the database, etc.). Otherwise, you should seriously think about the right way to implement this method.</p> <p>Third, call <code>demjson.JSON.encode(instance)</code> and you have what you want.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload