Django:为反向ForeignKey定义名称 [英] Django: define a name for reverse ForeignKey

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

问题描述

我有两个模型:

class Foo(models.Model):
    foo_field = ...

class Bar(models.Model):
    foo = models.ForeignKey(Foo, on_delete=models.CASCADE)
    bar_field = ...

,我可以使用以下方式访问与Foo相关的所有Bar实例:

and I can access all Bar instances related to a Foo with:

Foo.bar_set.all()

是否可以更改像 ManyToManyField中的反向名称,这样我就可以这样写:

Is there a way to change the 'reverse name', like in ManyToManyField, so that I can write:

Foo.bars.all()

推荐答案

是,使用 related_name

class Foo(models.Model):
    foo_field = ...

class Bar(models.Model):
    foo = models.ForeignKey(Foo, related_name="bars", on_delete=models.CASCADE)
    bar_field = ...

这篇关于Django:为反向ForeignKey定义名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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