Login

Call a manager method on any model with a filter

Author:
coleifer
Posted:
May 13, 2010
Language:
Python
Version:
1.1
Tags:
template-filter
Score:
3 (after 3 ratings)

Often I want to call a custom manager method in the template, something like Snippet.objects.get_latest(). I hate writing custom templatetags to do all that work, so instead I've written a filter that will work for any. Here's how I use it:

{% for snippet in "cab.snippet"|call_manager:"top_rated"|slice:":5" %}
 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 7 years, 5 months ago
  2. Easier chainability with custom QuerySets by bendavis78 3 years, 3 months ago
  3. Allow filtering and ordering by counts of related query results by exogen 8 years, 2 months ago
  4. Tatsypie: additional list endpoints for custom Model's manager methods by migajek 2 years, 7 months ago
  5. Functional Filters by waterson 7 years, 9 months ago

Comments

Please login first before commenting.