Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自另一个模型的Django外键引用_Django_Foreign Key Relationship - Fatal编程技术网

来自另一个模型的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
函数