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()
- [Django]-ManyRelatedManager not Iterable. Think I'm trying to pull my objects out incorrectly
- [Django]-Running ./manage.py migrate during Heroku deployment
- [Django]-Create Django model or update if exists
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
- [Django]-Django. A good tutorial for Class Based Views
- [Django]-How do I pass template context information when using HttpResponseRedirect in Django?
- [Django]-Cannot set Django to work with smtp.gmail.com
Source:stackexchange.com