来自另一个模型的Django外键引用
我有以下型号:来自另一个模型的Django外键引用,django,foreign-key-relationship,Django,Foreign Key Relationship,我有以下型号: 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 = mod
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']
如何为Author创建一个属性,允许我访问其书籍?您不需要在
Author
中创建新属性。您可以按照ForeignKey
关系反向获得特定作者编写的书籍,如下所示:
author = Author.objects.get(name='George Orwell')
books = author.book_set.all()
当您在book
和Author
之间创建ForeignKey
关系时,默认情况下,Django会创建book\u set
函数