开发者

Using __init__ in django to annotate a model with extra information

I wrote an __init__ method for one of my models that adds some auxiliary information to the object by dynamically adding an attribute to the object that does not reflect a column in the database:

class MyModel(models.Model):
    title = Models.CharField()
    description = Models.TextField()

    def __init__(self, *args, **kwargs):
        self.aux_info = "I'm not in the database!"

This seemed to be working fine, but I found a case where it does not work. I have some code in a view where I set a status variable and package up a list of MyModels into json like so:

from django.core import serializers 
from django.utils import simplejson 

...

# have to use serializers for django models
serialized_items = serializers.serialize("json", itemlist)
data["items"] = serialized_items # serialized_items is now a string
data["status"] = status

# package up data dict using simplejson for python objects
resp = simplejson.dumps(data)
return HttpResponse(resp, mimetype="application/javascript")

The problem seems to be that django's serializers only serialize the 开发者_Go百科model fields and not all attributes of the object so aux_info does not come through. I'm also pretty sure that using both serializers and simplejson is not the right way to do this. Thanks for any help!


Try usung the serialiser's optional fields argument.

serialized_items = serializers.serialize("json", itemlist, fields=['.....', 'aux_info'])

May i also suggest that using the __init__ method to add fields is considdered bad form in django and would be much better achieved like so:

class MyModel(models.Model):
    title = Models.CharField()
    description = Models.TextField()

    def aux_info(self):
        return "I'm not in the database!"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜