0

I have seen several examples of using select_related to query foriegn key related data in queryset. Including this example. But I want to do it in reverse way as explained below.

class Book(models.Model):
    name   = models.CharField(max_length=50)
    author = models.ForeignKey(Author)

class Author(models.Model):
    name   = models.CharField(max_length=50)

I have seen queryset to fetch the data while querying the Book because Author is specified in books.Like this books = Book.objects.all().select_related("author") But I need to query Author and then get all the books related with it.Is there any way to do that.

pacman
  • 725
  • 1
  • 9
  • 28

1 Answers1

1

You should use related_name in the FK definition:

class Book(models.Model):
    author = models.ForeignKey(Author, related_name="books")

An then, from Author you can:

Author.objects.all().prefetch_related("books")

Check the docs for more info.

gmc
  • 3,910
  • 2
  • 31
  • 44
  • that works but I only get the id field when I send a response. all the other fields are not shown in the response – pacman Jun 06 '20 at 12:17
  • Also select_related wasnt working for me.Prefetch related did. – pacman Jun 06 '20 at 12:23
  • You are right, my bad. When you are getting a set of objects you use `prefetch_related`. Updated the answer – gmc Jun 08 '20 at 07:57