Django 自定义管理器
我正在查看一些代码,我很好奇这是否是一个好的做法。
class ToDoManager(models.Manager):
def scheduled(self):
"""
Returns QuerySet of all things to be done.
"""
return self.filter(...)
class ImpStuff(models.Model):
....model definition
objects=TodoManager
我总是看到自定义管理器覆盖 get_query_set (释义)方法。这是处理事情的好方法吗?
I'm looking at some code and I'm curious whether this is good practice.
class ToDoManager(models.Manager):
def scheduled(self):
"""
Returns QuerySet of all things to be done.
"""
return self.filter(...)
class ImpStuff(models.Model):
....model definition
objects=TodoManager
I've always seen the custom manager override the get_query_set (paraphrasing) method. Is this a good way to handle things instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用模型管理器来包装复杂的 ORM 查询是非常 DRY 的做法,值得推荐。您可以向这些方法添加参数并节省大量代码:
然后您只需执行以下操作即可:
管理器在许多开源 Django 应用程序中使用,可在 Github 上找到。
Using model managers for wrapping complex ORM queries is something very DRY and recommended. You can add parameters to those methods and save yourself a lot of code:
Then you just do:
Managers are used in a lot of open source Django apps, available on Github.
我以前做过这个。效果很好。因此,除非您查看我的代码,否则世界上显然有两个人认为这很有用。
它不是覆盖
get_query_set
的替代 - 它提供了其他获取(过滤)实例的方法。你可以同时做这两件事(在合理的范围内)。您预计会遇到什么问题?
PS 这种方法也用在 Pro Django,第 274 页以后,其中使用
most_recent()
等方法扩展了 Manager。i've done this before. it worked fine. so unless you are looking at my code, there are apparently two people in the world that find this useful.
it's not an alternative to overriding
get_query_set
- it provides additional ways of getting (filtered) instances. you can do both at the same time (within reason).what problems are you expecting?
PS this approach is also used in Pro Django, page 274 onwards where a Manager is extended with methods like
most_recent()
.