SoFunction
Updated on 2024-11-19

django model object serialization example

Mention serialization and deserialization, usually think of json, xml. In the development of J2EE, this is a very common technology , such as a java class and xml serialization and deserialization between , we can xstream to achieve , if it is with the conversion between json, we can pass or to achieve . There are many methods, but also common methods.

But in python, we often use json serialization, python2.7 has included the json package, this is also changed from simplejson base. This json package mainly provides dump,load to realize the serialization and deserialization between dict and string, it's very convenient to complete, you can refer to this article python json. but now the problem is that this json package can't serialize the instances of the objects inside the django's models.

After analyzing and searching the web, we found the following solutions.

Use the from import serializers method to implement

from  import serializers
data = ("json", ())
data1 = ("json", (myfield1=myvalue))

The above two are fine because the serialized object is a Queryset and therefore successful. But the problem comes when you get a concrete instance with (id=myid)

data = ("json", (id=myid))

The following error is sure to occur.

for obj in queryset: TypeError: 'SomeModel' object is not iterable

One look at the error shows that (id=myid) is not iterable because it returns a concrete instance, not a collection object. That's why the error is reported.

From the above analysis, we can see that django's serializers only support queryset, but not model instances, so how to achieve it?

1. We model this single object as a collection ourselves, and then remove the "[" "]" symbols before and after.

from  import simplejson
from  import models
from  import serialize,deserialize
from  import QuerySet
from  import TestCase

class MyEncoder():
   """ Encoding base class inherited from simplejson for handling complex types of encoding
   """
   def default(self,obj):
       if isinstance(obj,QuerySet):
         """ Querysetan actual example
         Direct useDjangoBuilt-in serialization tools for serialization
         But if you return directly to theserialize('json',obj)
         followsimplejsonSerialization is treated as a string.
         Then there will be extra double quotes before and after
         So here's how to get the serialized object first
         followed bysimplejsonDeserialize once
         Get a standard dictionary(dict)boyfriend
         """
         return (serialize('json',obj))
       if isinstance(obj,):
         """
         If a single object is passed in, the difference from a QuerySet is that
         Django does not support serializing individual objects.
         Therefore, a single object is first used to construct an array of only one object
         This can be seen as a QuerySet object.
         and then use Django to serialize it.
         as if it were a QuerySet.
         But since the serialized QuerySet will be surrounded by '[]'s
         so we use string[1:-1] to remove it.
         '[]' from the serialized QuerySet.
         """
         return (serialize('json',[obj])[1:-1])
       if hasattr(obj, 'isoformat'):
         # Handle date types
         return ()
       return (self,obj)

def jsonBack(json):
   """  carry outJsonDeserialization of strings
     generally speaking,webPOST(orGET)
     The parameters contained in thejsondigital
     for example,expense or outlayPOSTOne of the parameters passed in was akey valueThe key-value pairs are
     ['update']
     = "[{pk:1,name:'changename'},{pk:2,name:'changename2'}]"
     To put thisvaluecarry out反序列化
     则可以使expense or outlayDjangoBuilt-in serialization and deserialization
     But here's the thing.
     传回的有可能是代表单个boyfriend的jsonstring (computer science)
     as if:
     ['update'] = "{pk:1,name:'changename'}"
     This is, since Django can't handle individual objects
     So do the proper processing
     Model it as an array, that is, surround it with '[]'
     and then deserialize it
   """
   if json[0] == '[':
     return deserialize('json',json)
   else:
     return deserialize('json','[' + json +']')

def getJson(**args):
   """ Serializing objects with MyEncoder, a custom rule class
   """
   result = dict(args)
   return (result,cls=MyEncoder)

In the above example , a custom serialization rule class MyEncoder , used to handle the collection or collection of objects , and then implement a variable parameter utility method getJson, used to pass multiple parameters , and will be serialized together . There is also a deserialized object method jsonBack, accepts a json representing an object or collection of objects and returns a collection of objects. In this way it can be very good to use with SimpleJson and Django to complete the serialization work!

2. directly utilize the json package provided by python 2.7, or use simplejson can be

First of all, you need to add a method toJSON in the definition of django model, using the django model can access _meta.fields to get the relevant attributes and get, the example is as follows

class Category():
  autoid = (primary_key=True)
  email=(max_length=150,blank=False)
  comtype=(max_length=20,blank=False)
  catname=(max_length=150,blank=False) 
  
  def __unicode__(self):
    return '%s' % ()
  
  def toJSON(self):
    import json
    return (dict([(attr, getattr(self, attr)) for attr in [ for f in self._meta.fields]]))

Now use django to look up the data and convert it to json

row=(autoid=23) print ()

You will find that the conversion was successful. Of course, this toJSON method, if you require better readability, you can write it like this

def toJSON(self):
  fields = []
  for field in self._meta.fields:
    ()

  d = {}
  for attr in fields:
    d[attr] = getattr(self, attr)

  import json
  return (d)

Additional knowledge:django model class serializer ModelSerializer

1. Definitions

Let's say we create a BookInfoSerializer.

class BookInfoSerializer():
  """Book Data Serializer."""
  class Meta:
    model = BookInfo
    fields = '__all__'

model Specifies which model class to refer to.

fields Specifies which fields of the model class are generated for the

2. Designation of fields

1) Use fields to specify fields, the __all__ table name contains all fields, or you can write which fields are specific, such as

class BookInfoSerializer():
  """Book Data Serializer."""
  class Meta:
    model = BookInfo
    fields = ('id', 'btitle', 'bpub_date')

2) Use exclude to make it clear which fields to exclude

class BookInfoSerializer():
  """Book Data Serializer."""
  class Meta:
    model = BookInfo
    exclude = ('image',)

3) By default ModelSerializer uses primary key as the associated field, but we can use depth to simply generate a nested representation, depth should be an integer indicating the number of nested levels. For example:

class HeroInfoSerializer2():
  class Meta:
    model = HeroInfo
    fields = '__all__'
    depth = 1

4) Specify read-only fields

Read-only fields can be specified via read_only_fields, i.e., fields that are only used for serialized output

3. Adding additional parameters

We can use the extra_kwargs parameter to add or modify the original option parameters for the ModelSerializer

class BookInfoSerializer():
  """Book Data Serializer."""
  class Meta:
    model = BookInfo
    fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment')
    extra_kwargs = {
      'bread': {'min_value': 0, 'required': True},
      'bcomment': {'min_value': 0, 'required': True},
    }

Above this django model object serialization example is all I have shared with you, I hope to give you a reference, and I hope you support me more.