0

I want to get all Blogs in one query, and at the same time, I want to know each Blog's Entry(or Entries), if the Blog has.

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

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

Like access the blog.ENTRY attributes. Here is the way come to mind at first. 1) get all Blogs, 2) set each Blog ENTRY attr with its entries:

for blog in Blog.objects.all():
    entry = Entry.objects.filter(blog=blog)
    setattr(blog, 'ENTRY', entry)

But I want to do this in just one query, because I don't want to do Entry filter query in the for loop.

Liao Zhuodi
  • 3,144
  • 5
  • 26
  • 46
  • Not sure what you're trying to do. Each blog already has an attribute, `entry_set`, which is a queryset of the related entries. – Daniel Roseman Jul 07 '17 at 14:13
  • Check out this thread and the Django docs for `select_related`: https://stackoverflow.com/questions/33230540/django-select-related-when-to-use-it – whp Jul 07 '17 at 14:13
  • Sorry, read your question too fast, this is a better thread explaining `select_related` and `prefetch_related`: https://stackoverflow.com/questions/23121850/select-related-with-reverse-foreign-keys – whp Jul 07 '17 at 14:20
  • What exactly you want to do? – Astik Anand Jul 07 '17 at 16:06

1 Answers1

0

Code:

Entry.objects.all().select_related('blog')

will fetch all Entry objects and populate it's blog attribute in single quest.

Doing same with Blog model is not possible in single query as relation is one-to-many.

To get better idea of what is possible and what is not, look at recommended in comments topics related to select_related and prefetch_related. Especially second one.

Zada Zorg
  • 2,778
  • 1
  • 21
  • 25