Ticket #8044: random.diff
File random.diff, 1.7 KB (added by , 16 years ago) |
---|
-
django/template/defaultfilters.py
12 12 from django.utils.translation import ugettext, ungettext 13 13 from django.utils.encoding import force_unicode, iri_to_uri 14 14 from django.utils.safestring import mark_safe, SafeData 15 15 from django.db.models.query import QuerySet 16 16 register = Library() 17 17 18 18 ####################### … … 475 475 length_is.is_safe = True 476 476 477 477 def 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) 480 493 random.is_safe = True 481 494 482 495 def slice_(value, arg): -
docs/templates.txt
1641 1641 1642 1642 Returns a random item from the given list. 1643 1643 1644 If the list is really a queryset, will limit the queryset to a random item 1645 instead 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 1644 1650 For example:: 1645 1651 1646 1652 {{ value|random }}