django generate json

An approach to generating custom JSON from your objects, mostly a repost of http://theoephraim.com/2011/04/json-encoding-custom-django-models/:

from django.utils.simplejson import JSONEncoder

class CustomObjectEncoder(JSONEncoder):
	def default(self, obj):
		if isinstance(obj,MyModel):
			return obj.to_dict()
		return JSONEncoder.default(self, obj)

class MyModel(models.Model):
  # how our custom json will look like
  def to_dict(self):
    return {"id":self.id,"label":self.name,"value":self.name}

# view that generates json
def autocomplete(request):
  mimetype = "application/javascript"
  # need to call list, because querysets are not serializable
  data = list(MyModel.objects.all())
  return HttpResponse(CustomObjectEncoder().encode(data),mimetype)


0 Responses to “django generate json”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog Stats

  • 238,127 hits

%d bloggers like this: