anttiu
anttiu

Reputation: 49

Django foreign key reference from another model

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?

Upvotes: 3

Views: 4916

Answers (1)

gtlambert
gtlambert

Reputation: 11971

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.

Upvotes: 6

Related Questions