I have a Django application that defines a one-to-many model relationship. The models look like this:
from django.db import models
# Create your models here.
class StreamNetwork(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Stream(models.Model):
name = models.CharField(max_length=50)
custom_url = models.CharField(max_length=100, null=True)
network = models.ForeignKey(StreamNetwork)
score = models.SmallIntegerField()
def __unicode__(self):
return self.name
Later on I want to serialize all my Stream entries into json. I do it like this:
from django.core.serializers import serialize
string = serialize(format, Stream.objects.all())
The expected result would be a simple serialized json version of a row in the database. Instead the output looks like this:
[
{
"pk" : 1,
"model" : "website.stream",
"fields" :
{
"network" : 2,
"score" : 53,
"name" : "DangerousDan1",
"custom_url" : null
}
},
...
In addition I would like to get the name of the streamnetwork in the output instead of the id.
So is there a Django way I can customize how the serialize output should be formatted?
Thanks for any helpful replies
Keep in mind that a QuerySet is more than just a simple database query, so the “expected result” should be that it contains additional information. One simple way to do what you want (and I’d say it’s a Django Way) is to define a model manager that returns only what you want. Something like:
then put
objects = StreamManger()in your Stream class, and you can access the stream as Stream.objects.all_serialized()Another way to do it would be to subclass QuerySet so it returns only the information you want and then use the serialize() method on the queryset, but I’ve never gotten into that and assume it would require some knowledge of how QuerySets work under the hood (it might be slightly more efficient than my solution, but since the point is to serialize everything and you want to do a foreign key lookup on each entry to find the network name, I assume you not working with a huge amount of data).
EDIT: regarding your comment on Rob’s solution, see the documentation for serialize() – you can define the fields you want to be serialized, but I don’t think it supports foreign key lookups, and you’ll still get it in the QuerySet format (pk, model, and fields).