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

前端 未结 3 884
天命终不由人
天命终不由人 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:00

    Just add related_name to ForeignKey and you will be able to get all books made by an author.

    For example:

    class Book(models.Model):
        ...
        author = models.ForeignKey('Author', related_name='books')
        ...
    

    and later...

    author = Author.objects.get(pk=1)
    books = author.books.all()
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-14 11:08

    You did something weird in line

    books = Book.objects.get(pk=object_instance.pk)
    

    Just delete it. You will be able to use author.book_set. You can also use related_name parameter of ForeignKey.

    Look here for details: https://docs.djangoproject.com/en/1.9/ref/models/fields/#foreignkey

    0 讨论(0)
提交回复
热议问题