I have following models:
class Author(models.Model):
name = models.CharField(max_length=255, unique=True)
"""books = Attribute which allows an access to books from this author"""
class Meta:
ordering = ['name']
class Book(models.Model):
name = models.CharField(max_length=255, unique=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
class Meta:
ordering = ['name']
How I can make an attribute to Author, which allows me to get an access to its books?
You don't need to create a new attribute in Author. You can get the books written by a specific author by following the ForeignKey relationship backwards as follows:
author = Author.objects.get(name='George Orwell')
books = author.book_set.all()
The book_set function is created by default by Django when you create the ForeignKey relationship between Book and Author.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With