python - Using __init__ in django to annotate a model with extra information -
I wrote a __init__ method for one of my models that added an object to a dynamically object for the object Some helpful information combines it 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!" It was working fine, but I got a case where it does not work. I have some code in a scene where I set a condition variable and a list of MyModels in JSON: from django.core import serializers Django.tills import importation ... #designs that use serializers for the model serialized_items = serializers.serialize ("json", itemlist) data ["items"] = serialized_items # serialized_items now a string data ["status"] = Integrate data detox using the easy-to-use position # python objects. Response = simplejson.dumps Returns HttpResponse (resp, mimetype = "application / javascript") The problem is that the serializer of the Dedgegen will only serialize the model field and all the attributes of the object Do not do it, so aux_info does not come through it. I'm pretty sure that this is not the right way to use both serializers and simplejson. Thanks for any help!
Try to use the serial's optional field logic.
serialized_items = serializers.serialize ("json", item list, field = ['.....', 'aux_info']) I can also suggest that the method to add a field> __ init __ method has been made into a bad form in the dynamic and it would be much better as: Class MyModel (models.Model): title = Models.CharField () Description = Model. TextField () def aux_info (self): return "I'm not in the database!"
Comments
Post a Comment