Django模型与管理器 [英] Django Model vs. Manager

查看:300
本文介绍了Django模型与管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不太确定有什么区别.似乎Manager所做的一切就是拥有与模型相关的一堆功能.但是这些功能也可以放在模型中....

Not really sure what the difference is. Seems like all the Manager does is have a bunch of functions related to the Model. But these functions could also be placed in the Model too....

Django文档对管理器的描述如下,

Django documentation describes the Manager as follows,

管理器是用于执行数据库查询操作的接口 提供给Django模型.

A Manager is the interface through which database query operations are provided to Django models.

那么,与该简单抽象相比,管理器在本质上还有其他区别吗?

So is there anything else fundamentally different about the Manager than this simple abstraction?

还是一个更好的问题:在模型与管理器中应定义哪些方法?有实际差异还是只是风格差异?

Or a better question: what methods should be defined in the Model vs. the Manager? Is there an ACTUAL difference or just stylistic one?

推荐答案

在Django中,模型管理器是模型用来通过其执行数据库查询的对象.每个Django模型都有至少一个管理器,即objects,您可以创建自己的管理器来更改默认行为.

In Django, a models' manager is the object through which models perform database queries. Each Django model has at least one manager, which is objects, and you can create your own to change the default behavior.

所以,你的声明

但是这些功能也可以放在模型中

But these functions could also be placed in the Model too

嗯,不是真的,因为该模型仍然依赖于默认管理器来检索查询集.

Well, not really because the model is still depending on the default manager to retrieve the queryset.

让我尝试用一​​个例子来解释.可以说您的应用程序需要一个模型对象来仅显示状态为published的对象.现在,MyModel.objects.all()检索所有内容,并且您必须每次都指定过滤器MyModel.objects.filter(published=True).

Let me try to explain in terms of an example. Lets say your application requires a model object to show only objects with a status of published. Now, MyModel.objects.all() retrieves everything, and you would have to specify the filter MyModel.objects.filter(published=True) every single time.

现在,您可以覆盖此默认行为.

Now, you can override this default behavior.

class MyModelAdmin(admin.ModelAdmin):

    def queryset(self, request):
        return MyModel.objects.filter(published=True)

我们刚才所做的是覆盖默认管理器的默认行为.

What we just did was override the default behaviour of the default manager.

现在,假设您想要一切,您可以执行类似的操作

Now, lets say you want everything, You can do something like

class MyModelAdmin(admin.ModelAdmin):    
    def queryset(self, request):
        return MyModel.objects.filter(published=True)
    def all_objects(self, request):
        return MyModel.objects.all()

在访问所有对象时,只需执行

and while accessing all objects, just do

MyModel.objects.all_objects()

也可能有多个经理使用单一模型

简而言之,管理者在访问模型的查询集方面具有很大的灵活性.

In short, managers give a lot of flexibility in terms of accessing querysets to the model.

这篇关于Django模型与管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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