How to use Django Custom Model Managers

533 views Asked by At

How do you determine whether something should be a separate custom model manager or a function of an existing model manager?

For example I could create a single model manager whose queryset is all instances of the model. Then I could create functions within that manager to return subsets like - only instances listed as private, or public.

Alternately - I could create a separate custom model manager for each of those returning the queryset of private instances and public instances.

eg:

Video.objects.get_private()
Video.objects.get_public()

or

Video.private.all()
Video.public.all()
1

There are 1 answers

0
Paulo Scardine On

From the zen of Python:

>>> import this
The Zen of Python, by Tim Peters

...    
Explicit is better than implicit.
...
>>> 

May be your situation is more complicated than I inferred by your code sample, but IMHO you should just use a filter:

Video.objects.filter(private=False)

If you are trying to spare type strokes for common filters, remember querysets are lazy, so you can store them:

private_videos = Video.objects.filter(private=False)
...
private_videos.objects.filter(director='Frederico Felini').order_by('-year')

The first assignment will not trigger communication with the database. Spare custom managers for more complex stuff.

I've seen this pattern of lots of model methods and/or custom managers because Django template system sux^H^H^His intentionally handicapped (you can't call methods with arguments without creating template filters). If it is the case, switch the template layer to Jinja2.