I have two models:
class Author(models.Model);
name = models.CharField(max_length=255)
class Book(models.Model):
title = models.CharField(max_length=255)
authors = models.ManyToManyField(Author, null=True, blank=True)
Now, I want the info of all the books. So, I did:
book_info = Book.objects.all().values('title', 'authors__name')
And, it gives an output like (for 1 book having 2 authors):
[{'title': u'book1', 'authors__name': u'author1'},{'title': u'book1', 'authors__name': u'author2'}]
What I wanted was something like:
[{'title': u'book1', 'authors': [{'name':u'author1'},{'name':u'author2'}]}]
I may have more fields in the author model, so would like to get those fields as well.
Can I do this in a single query?
What can I do to get something like the desired result?
Django 1.4
Great question, use prefetch_related:
Django 1.3
prefetch_related was introduced in Django 1.4. For Django 1.3, you need django-selectreverse:
Using django-selectreverse:
To avoid doing two queries as in the descriptive answer from @jpic, you could just manually merge your results afterwards. It feels a bit hacky to me, but it works.
The merge_values function is take from this gist