1

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.

nickbusted
  • 1,029
  • 4
  • 18
  • 30

2 Answers2

1

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])
Community
  • 1
  • 1
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Previous answer was not correct because then e was not iterable hence was not serializable. So I edited it. – ruddra Jun 30 '14 at 08:52
  • Thank you! Work very well. However, I was not able to return entries, but only blogs. I will post another answer that allowed me to do both. – nickbusted Jul 01 '14 at 00:03
1

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)
Community
  • 1
  • 1
nickbusted
  • 1,029
  • 4
  • 18
  • 30