Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
anttiu Avatar asked Jul 08 '26 23:07

anttiu


1 Answers

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.

like image 54
gtlambert Avatar answered Jul 11 '26 19:07

gtlambert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!