11

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 documentation describes the Manager as follows,

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
reedvoid
  • 1,203
  • 3
  • 18
  • 34
  • 2
    In practice, I'd say the manager is how Django does it, and doing it directly in the model is a shortcut you can do (since generally you set the Manager instance as a model property). Using the manager is usefull to override the "get_queryset" methods, what will automatically change what is shown in the admin pages. But there is not fundamental change: you can call operations on a model everywhere if you import the module, that's Python atrocity: no privates ^^ – Ricola3D Jun 26 '13 at 12:56
  • 1
    Manager is a python object that manage the connections between your app and the specific database you have defined in settings.py. Models are how you define your app's tables inside your db. – Below the Radar Jun 26 '13 at 13:05

1 Answers1

13

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.

karthikr
  • 97,368
  • 26
  • 197
  • 188