Login

Call a manager method on any model with a filter

Author:
coleifer
Posted:
May 13, 2010
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.