来自另一个模型的Django外键引用

时间:2016-02-23 15:58:47

标签: 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']

如何为Author创建一个属性,允许我访问其书籍?

1 个答案:

答案 0 :(得分:4)

您无需在var query = itemTable.query() query.fetchLimit = 300 query.orderByDescending("__createdAt") 中创建新属性。您可以按照以下Author关系向后获取特定作者撰写的书籍:

ForeignKey

当您在author = Author.objects.get(name='George Orwell') books = author.book_set.all() book_set之间建立ForeignKey关系时,Django默认创建Book函数。