[Django]-How to get all objects referenced as ForeignKey from given field in a module in django

38👍

✅

You don’t need to create a separate field in Authors model

class Author(models.Model):
    AuthorName = models.CharField(max_length=255, unique=True)

class Book(models.Model):
    BookName = models.CharField(max_length=255)
    Author = models.ForeignKey('Author')

You can get all books of a particular author like:

author = Author.objects.get(id=1)
books = author.book_set.all()

Learn more about backward relationships here

17👍

Just add related_name to ForeignKey and you will be able to get all books made by an author.

For example:

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

and later…

author = Author.objects.get(pk=1)
books = author.books.all()

4👍

You did something weird in line:

books = Book.objects.get(pk=object_instance.pk)

Just delete it. You will be able to use author.book_set. You can also use related_name parameter of ForeignKey.

See the Django docs: https://docs.djangoproject.com/en/4.0/ref/models/fields/#foreignkey

Leave a comment