关于Django中的外键关系感到困惑

时间:2015-03-07 15:26:11

标签: python django database database-design

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

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

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

现在我还希望将特定作者写的所有文章存储在“作者”类中,以便我可以在我的视图的“作者”页面中显示它们。

如何创建作者模型?

class Author(models.Model):
     published_articles = ?

2 个答案:

答案 0 :(得分:0)

解决方案(如果您确实要保存该关系):

如上所述here

  

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

class Author(models.Model):
     published_articles = models.ManyToManyField('your_actual_app_label.Article')

解决方案(如果您只想要一种方法来访问author的author_articles):

如上所述here

  

Django还为关系的“其他”方创建API访问器 - 从相关模型到定义关系的模型的链接。例如,博客对象 b 可以通过 entry_set 属性访问所有相关条目对象的列表:的 b.entry_set.all()

author = Author.objects.first()
author.article_set.all()

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

答案 1 :(得分:0)

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

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)

我建议你看看docs,因为他们清楚地证明了你应该如何处理你的问题。