Call a manager method on any model with a filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.db.models.loading import get_model
from django.db.models.query import QuerySet
from django import template

register = template.Library()

@register.filter
def call_manager(model_or_obj, method):
    # load up the model if we were given a string
    if isinstance(model_or_obj, basestring):
        model_or_obj = get_model(*model_or_obj.split('.'))

    # figure out the manager to query
    if isinstance(model_or_obj, QuerySet):
        manager = model_or_obj
        model_or_obj = model_or_obj.model
    else:
        manager = model_or_obj._default_manager

    return getattr(manager, method)()

More like this

  1. Custom managers with chainable filters by itavor 4 years, 3 months ago
  2. Alternate method of autoloading Django models in ipython by drewr 4 years, 4 months ago
  3. Easier chainability with custom QuerySets by bendavis78 2 months, 1 week ago
  4. Case-insensitive lookup by default by sciyoshi 4 years, 10 months ago
  5. Simple random file CAPTCHA by jeverling 2 months, 2 weeks ago

Comments

(Forgotten your password?)