Select_Related and JSON - How to serialize foreign key objects

Suppose I have 2 models:

class Blog(models.Model):
    name = models.CharField(max_length=100)

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)

I need to return all entries with corresponding blogs in JSON format:

TO_JSON = serializers.serialize('json', Entry.objects.select_related('blog').filter(...))

TO_JSON contains all entries I need, but with no blogs.

Answers


Edit

From https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.select_related, you can try like this:

e = Entry.objects.select_related('blog').filter(...)
return serializers.serialize('json', [x.blog for x in e])

Thanks to @bento who suggested the following answer, which is available at django serialize foreign key objects:

entries = Entry.objects.select_related('blog').filter(...)
list = []
for row in entries:
        list.append({'blog_title':row.blog.title, 'entry_title': row.title})
return json.dumps(list)

Need Your Help

Learn to actually write in Java or just understand the code?

java android ios iphone unity3d

Sorry for the newbie question but I really need to understand this .

Padding an image for use in wxpython

python icons wxpython python-imaging-library padding

I'm looking for the most efficient way to 'square' an image for use as an icon. For example, I've got a .png file whose dimensions are 24x20.I don't want to change the 'image' part of the image in ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.