Reputation: 1954
Let's say I have a Django model
class Book(models.Model):
title = models.CharField()
author = models.ForeignKey(Author)
is_on_loan = models.BooleanField()
How do I get the JSON representation of the Book
? I could easily write something like
import json
def get_json(self):
json_rep = {}
json_rep['title'] = self.title
json_rep['author'] = self.author.full_name
json_rep['is_on_loan'] = self.is_on_loan
return json.dumps(json_rep)
But is there a better way?
Upvotes: 2
Views: 4210
Reputation: 15105
This is called serializing. There are django native serializers, you can read about them in the docs (https://docs.djangoproject.com/en/1.9/topics/serialization/), but the basic usage is
from django.core import serializers data = serializers.serialize("json", YourModel.objects.all())
That said, Django serializers have some limitations that might or might not cause problems for you.
If you are using or considering using Django REST Framework, it has excellent, flexible serializer/deserializer architecture. There are other serializing libraries out there that you might want to google for.
Upvotes: 3
Reputation: 55448
Yes there is a better way, use the built-in Django JSON serializer
from django.core import serializers
json_data = serializers.serialize('json', Book.objects.all())
Upvotes: 1