3

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.