ant*_*tiu 2 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 = models.CharField(max_length=255, unique=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
class Meta:
ordering = ['name']
Run Code Online (Sandbox Code Playgroud)
如何为 Author 设置一个属性,以便我可以访问其书籍?
您不需要在Author. 您可以通过以下ForeignKey关系向后获取特定作者撰写的书籍:
author = Author.objects.get(name='George Orwell')
books = author.book_set.all()
Run Code Online (Sandbox Code Playgroud)
book_set当您ForeignKey在Book和之间创建关系时,该函数默认由 Django 创建Author。
| 归档时间: |
|
| 查看次数: |
2878 次 |
| 最近记录: |