gpt4 book ai didi

python - 反向外键查找

转载 作者:太空宇宙 更新时间:2023-11-04 01:43:45 25 4
gpt4 key购买 nike

我是 Django 的新手,并且仍在尝试打破旧的 PHP 习惯。下面是两个模型。为了让事情变得困惑,它们存在于不同的文件中,在不同的应用程序中......

#article.models
from someapp.author.models import Author

class Article(model.Model):
...
author = models.ForeignKey(Author)


# author.models
class Author(model.Model):
...

我希望能够从这个模式中获取某个作者的所有文章。像这样的东西:
作者 = 作者(pk=1)
文章=作者.文章

我的第一 react 是编写一个方法,根据作者 ID 在文章模型中进行简单的查找。由于单独的文件,这里发生的是一个永无止境的包含循环。 Article needed Author imported 用于 ForeignKey 和 Author needed article included 用于模型查找。这感觉很老套而且是错误的。我宁愿以正确的方式去做...那么,Django 的方式是什么?

最佳答案

我想这就是你要的...

class Article(model.Model):
...
author = models.ForeignKey(Author, related_name='articles')

附带说明一下,默认情况下不更改任何内容,我认为这对您有用...

article.author_set

但要保持您上面提到的 article.authors 语法,您可以使用 related_name 自行指定。

关于python - 反向外键查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2099037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com