反向外键查找 [英] Reverse ForeignKey lookup

查看:97
本文介绍了反向外键查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Django and am still trying to break old PHP habits. Below are two models. To make things confusing they live in separate files, in different apps...

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

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


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

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

From this schema I want to be able to get all the articles by an author. Something like:
author = Author(pk=1)
articles = author.articles

我的第一反应是编写一种基于作者ID在文章模型中进行简单查找的方法.由于单独的文件,这里发生的是一个永无止境的包含循环.所需的文章已导入作者以用于ForeignKey,已包含的作者所需的文章用于模型查找.这感觉很拙劣而且是错误的.我宁愿以正确的方式来做...那么,Django的方式是什么?

My first reaction was to write a method that did a simple look up in the article model based on the authors ID. What happened here was a never ending inclusion loop because of the separate files. Article needed Author imported to use for the ForeignKey and Author needed article included to use for the model look up. This felt hacky and wrong. I would much rather do it the right way... So, what is the Django way?

推荐答案

我认为这就是您要的...

I think this is what you're asking for...

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

顺便说一句,默认情况下,不更改任何内容,我认为这对您有用...

On a side note, by default without changing anything you've got, I think this would work for you...

article.author_set

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

But to maintain the article.authors syntax you mention above, you can specify that yourself with related_name.

这篇关于反向外键查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆