How to get all objects referenced as ForeignKey from given field in a module in django

前端 未结 3 892
天命终不由人
天命终不由人 2020-12-14 10:35

I have two classes: Author and Book. I want class Authors to have an attribute that contains all books written by the said author, as referenced to as foreign key in the cla

3条回答
  •  伪装坚强ぢ
    2020-12-14 11:02

    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

提交回复
热议问题