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 6 years, 3 months ago
  2. Easier chainability with custom QuerySets by bendavis78 2 years, 1 month ago
  3. Allow filtering and ordering by counts of related query results by exogen 7 years ago
  4. Tatsypie: additional list endpoints for custom Model's manager methods by migajek 1 year, 5 months ago
  5. Functional Filters by waterson 6 years, 7 months ago

Comments

(Forgotten your password?)