Latest instances template filter

 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

  1. Allow template tags in a Flatpage's content by kylefox 5 years, 9 months ago
  2. Updated FileField / ImageField with a delete checkbox by tomZ 6 years, 1 month ago
  3. Call a manager method on any model with a filter by coleifer 3 years, 11 months ago
  4. Pad integers with leading zeros (template filter) by jcroft 6 years, 3 months ago
  5. mask_email filter by jkocherhans 7 years, 1 month ago

Comments

(Forgotten your password?)