How to get all objects referenced as ForeignKey from given field in a module in django
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
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()
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
.
Look here for details: https://docs.djangoproject.com/en/1.9/ref/models/fields/#foreignkey