Django Model Object Serialize By SpitEat

django model object 最简单的方法

s = NagiosHoststatus.objects.all()[0]
print s.__dict__


但是这个方法有一个缺点, 外键所关联的对象并不会被Serialize,


 class Model1(models.Model): name=models.CharField() child=models.ForeignKey(Model2) class Mode2(models.Model): field1=models.CharField() field2=models.IntegerField()

... { ... 'pk': <a_pk>, ... 'id': <an_id>, ... 'name': <a_name>, ... 'child_id': <id> ... }

我们希望的结果是这样的

... { ... 'pk': <a_pk>, ... 'id': <an_id>, ... 'name': <a_name>, ... 'child': { ... 'pk': <another_pk>, ... 'id': <another_id>, ... 'field1': <a_value>, ... 'field2': <another_value> ... } ... }


SpitEat出场了,

#coding=utf-8

from django.core.management import setup_environ
#from mytest import settings
import settings
setup_environ(settings)

from orm.models import NagiosHoststatus
from bus.status import get_hoststatus_id

from spiteat.djangosrz import *

s = NagiosHoststatus.objects.all()[0]
print s.__dict__
status_srz = ModelSrz(custom_for=NagiosHoststatus)
dd = status_srz.spit(s)
print type(dd), dd

print dd
print "end."



你可能感兴趣的:(Django Model Object Serialize By SpitEat)