Importing django model methods in json
I am trying to output a set of database records in JSON as follows:
def json_dbtable(request, p):
t = MyModel.objects.filter({some query})
s = serializers.get_serializer("json")()
re = s.serialize(t, ensure_ascii=False)
return HttpResponse(re, mimetype="application/json")
However, one of the fields i'm trying to return needs to change if it is null
, and to remedy this the model has a definition that is used as a property .e.g:
name = property(_get_useful_name)
So, to get to the开发者_运维问答 crux of the question. How can I include this "name" property in my json serialization as well as the raw field data?
The short answer is no, the long answer, is you could serialize your MyModel
instance yourself:
simplejson.dumps([{'pk': m.pk, 'name': m.name} for m in MyModel.objects.filter(...)])
I have written a serialization framework for Python called any2any which include (de)serializers for Django and which allows you to do that easily. It will be way cleaner than the DIY way. Hope that helps !
精彩评论