Django:如何从相关管理器访问原始实例?
我想在我的管理器方法 baz
中访问 Foo
实例 foo
:
foo.bar_set.baz()
baz
通常会采用以下参数Foo
类型:
BarManager(models.Manager):
def baz(self, foo=None):
if foo is None:
# assume this call originates from
# a RelatedManager and set `foo`.
# Otherwise raise an exception
# do something cool with foo
这样上面的第一个查询和下面的查询的工作方式相同:
Bar.objects.baz(foo)
Bar
将有一个指向 Foo
的外键:
class Bar(models.Model):
foo = models.ForeignKey(Foo)
objects = BarManager()
I would like to access the Foo
instance foo
within my manager method baz
:
foo.bar_set.baz()
baz
would normally take an argument of Foo
type:
BarManager(models.Manager):
def baz(self, foo=None):
if foo is None:
# assume this call originates from
# a RelatedManager and set `foo`.
# Otherwise raise an exception
# do something cool with foo
This way both the first query above and the following one works identically:
Bar.objects.baz(foo)
Bar
would have a ForeignKey to Foo
:
class Bar(models.Model):
foo = models.ForeignKey(Foo)
objects = BarManager()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
至少在 Django 2.1 中,您可以简单地执行以下操作:
foo.bar_set.instance
In Django 2.1 at least, you can simply do:
foo.bar_set.instance
如果我正确理解你想要什么,你需要这样做:
编辑:显然我完全没有抓住要点。你可以使用这样的东西(对于我的口味来说可能有点太“神奇”,但是哦好吧):
If I'm understanding what you want correctly, you need to do this:
Edit: apparently I managed to miss the point completely. You can use something like this (maybe a bit too "magic" for my taste, but oh well):