Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.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
Python 对Django的外键关系感到困惑_Python_Django_Database_Database Design - Fatal编程技术网

Python 对Django的外键关系感到困惑

Python 对Django的外键关系感到困惑,python,django,database,database-design,Python,Django,Database,Database Design,我正在为博客平台构建一个Django应用程序。在编写模型时,我陷入了数据库关系之间的混乱之中 在我的博客中,我的两个模型类是“Author”和“Article”。一篇特定的文章由一位/唯一的作者撰写。但是,一位“作者”写了几篇文章 class Article(models.Model): author_name = models.ForeignKey(Author) 现在,我还想将特定作者撰写的所有文章存储在“author”类中,以便在视图的“author”页面中显示它们 如何创建

我正在为博客平台构建一个Django应用程序。在编写模型时,我陷入了数据库关系之间的混乱之中

在我的博客中,我的两个模型类是“Author”和“Article”。一篇特定的文章由一位/唯一的作者撰写。但是,一位“作者”写了几篇文章

class Article(models.Model):
      author_name = models.ForeignKey(Author)
现在,我还想将特定作者撰写的所有文章存储在“author”类中,以便在视图的“author”页面中显示它们

如何创建作者模型

class Author(models.Model):
     published_articles = ?
解决方案(如果确实要保存该关系): 如上所述:

如果需要在尚未定义的模型上创建关系,可以使用模型的名称,而不是模型对象本身

解决方案(如果您只想访问作者的已发布文章): 如前所述:

Django还为关系的“另一方”(从相关模型到定义关系的模型的链接)创建API访问器。例如,Blog对象b可以通过Entry\u set属性访问所有相关条目对象的列表:b.Entry\u set.all()

明智地选择。
希望这有帮助:)

为什么不在作者模型中添加一个方法,以便从视图中轻松检索他的所有文章

class Article(models.Model):
    author_name = models.ForeignKey(Author)

class Author(models.Model):
    # ...
    def get_articles(self):
         "Returns the author published articles"
         return self.article_set.all()
那么在你看来,

def my_view(request):

    # Retrieve the author the way you see fit
    author = Author.objects.get(id=request.session['author'])

    articles = author.get_articles()
    context = {"articles": articles}
    return render(request, 'mytemplate.html', context)

我建议你看一下,因为它们以惊人的精确性清楚地展示了你应该如何处理你的问题

课堂文章中的ForeignKey(Author)字段将保持原样?非常感谢!如果可能的话,你能解释一下解决方案吗?这不是一个好的做法,因为这不是一个多对多的关系。@HarshGupta我已经更新了答案。根据您的用例进行选择。@FelixD。这取决于用例,一篇文章可能由许多作者撰写。在这种情况下,不需要外键关系。最好的Django已经提供了以下功能:
author.article\u set.all()
class Article(models.Model):
    author_name = models.ForeignKey(Author)

class Author(models.Model):
    # ...
    def get_articles(self):
         "Returns the author published articles"
         return self.article_set.all()
def my_view(request):

    # Retrieve the author the way you see fit
    author = Author.objects.get(id=request.session['author'])

    articles = author.get_articles()
    context = {"articles": articles}
    return render(request, 'mytemplate.html', context)