Writing templatetags is obnoxious. Say you have a small blurb on all your pages that shows the latest 5 comments posted to the site -- using this filter, you could write the following:
{% for comment in "comments.comment"|latest:5 %}
...display comment here...
{% endfor %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from django.db.models.loading import get_model
from django.db.models.query import QuerySet
from django.db.models.fields import DateTimeField, DateField
register = template.Library()
@register.filter
def latest(model_or_obj, num=5):
# 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
# get a field to order by, defaulting to the primary key
field_name = model_or_obj._meta.pk.name
for field in model_or_obj._meta.fields:
if isinstance(field, (DateTimeField, DateField)):
field_name = field.name
break
return manager.all().order_by('-%s' % field_name)[:num]
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 8 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 8 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 3 months ago
- Help text hyperlinks by sa2812 1 year, 4 months ago
Comments
Please login first before commenting.