python - django: How do you create a custom encoder for a JSON dump? -


i'm running type error, it's claiming <store: test store> not json serializable after running following code.

def storeliqour_view(request, store_id):      objects = storeliquor.objects.filter(storeid=store_id)     list_display = ['storeliquorid', 'storeid', 'storeprice', 'spi']      # extract information     data = [[getattr(obj, field) field in list_display] obj in objects]      #define response     response = {         'aadata': data,         'itotalrecords': itotalrecords,         'itotaldisplayrecords': itotaldisplayrecords,         'secho': request.get['secho']     }      #serialize json     s = bytesio()     json.dump(response, s, cls=mainencoder)     s.seek(0)     return httpresponse(s.read()) 

the <store: test store> in error comes me calling storeid field, foreign key store model. supposed return name of store, in case, "test store". produces typeerror.

i'm trying write custom encoder allow me return name of store based on storeid. can't seem figure out. have encoding decimals, code bellow shows, how continue? cool if change form html, maybe turn link.

class mainencoder(json.jsonencoder):      def default(self, obj):          if isinstance(obj, decimal):             obj = float(obj)         else:             obj = super(mainencoder, self).default(obj)         return obj 

django has own documentation serializing objects, see https://docs.djangoproject.com/en/1.7/topics/serialization/#serialization-formats-json (take care of choosing right django version in lower right corner)