Django Model vs. Manager

北战南征 提交于 2019-12-04 04:15:47

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.

So, your statement

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.

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()

It is also possible to have multiple managers to a single model

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!