Ticket #8044: random.diff

File random.diff, 1.7 KB (added by Idan Gazit, 16 years ago)

Patch for 'random' template filter to smartly handle querysets

  • django/template/defaultfilters.py

     
    1212from django.utils.translation import ugettext, ungettext
    1313from django.utils.encoding import force_unicode, iri_to_uri
    1414from django.utils.safestring import mark_safe, SafeData
    15 
     15from django.db.models.query import QuerySet
    1616register = Library()
    1717
    1818#######################
     
    475475length_is.is_safe = True
    476476
    477477def random(value):
    478     """Returns a random item from the list."""
    479     return random_module.choice(value)
     478    """
     479    Returns a random item from the list.
     480   
     481    If the value is a queryset, limits the queryset instead of evaluating
     482    and then choosing.
     483    """
     484    if isinstance(value, QuerySet):
     485        object_count = value.count()
     486        if not object_count:
     487            return None
     488        else:
     489            random_index = random_module.randint(0, object_count-1)
     490            return value[random_index]
     491    else:
     492        return random_module.choice(value)
    480493random.is_safe = True
    481494
    482495def slice_(value, arg):
  • docs/templates.txt

     
    16411641
    16421642Returns a random item from the given list.
    16431643
     1644If the list is really a queryset, will limit the queryset to a random item
     1645instead of evaluating it. See the `DB API documentation`_ on `limiting querysets`_.
     1646
     1647.. _DB API documentation: ../db-api/
     1648.. _limiting querysets: ../db-api/#limiting-querysets
     1649
    16441650For example::
    16451651
    16461652    {{ value|random }}
Back to Top