什么是“经理”?在Django? [英] What is a "Manager" in django?
问题描述
我已经阅读了官方Django 文档中的定义 ,我仍然对 Manager
的功能感到困惑。
I have read the definition in the official Django documentation, and I am still confused by what a Manager
does.
文档说,它们允许您对数据库表/模型进行操作,但我仍然不明白。
The documentation says that they allow you to operate on database tables/models, but I still don't understand this.
有人可以向我解释一下经理及其角色吗?
Can someone explain managers and their role to me? An answer with an example would be preferable.
推荐答案
经理通常是django程序员隐藏的东西,而django用来在两者之间进行接口模型
代码和数据库后端。
A manager is usually something hidden away from django programmers that django uses to interface between model
code and the database backend.
查询Django ORM时,可通过调用
When you query the django ORM, you do so through calls to
from my_app.models import MyModel
mms = MyModel.objects.all()
在这种情况下,函数的对象
部分是管理器返回的内容。如果您希望MyModel仅获得 blue
MyModel
实例(数据库可能包含 red
模型),那么您可以创建一个管理器并以此来入侵模型
In this case, the objects
part of the function is what is returned by the manager. If you wanted MyModel to only ever get blue
MyModel
instances (the database might contain red
models too) then you could create a manager and hack your model thus
class BlueManager(models.Manager):
def get_query_set(self):
return super(BlueManager, self).get_query_set().filter(colour='Blue')
class MyModel(models.Model):
colour = models.CharField(max_length=64)
blue_objects = BlueManager()
并调用
MyModel.blue_objects.all()
只会返回颜色为
的对象为 blue
。注意,这是筛选模型的一种非常差的方法!
would only return objects with colour
as blue
. Note, this is a very poor way to filter models!
如果需要,通常需要修改 Manager
接口他们将修改经理通常返回的 QuerySet
,或者如果您需要添加表级查询(而不是常规的Django行级),则需要修改。用于管理者的文档非常完整,并包含一些示例。
One would usually need to modify a Manager
interface if they were going to modify the QuerySet
s that a manager would usually return or if you needed to add "table" level queries (rather than regular django "row" level). The documentation for managers is quite complete and contains several examples.
这篇关于什么是“经理”?在Django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!