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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.