- Author:
- hawkeye
- Posted:
- May 11, 2007
- Language:
- Python
- Version:
- .96
- Tags:
- filter
- Score:
- 1 (after 1 ratings)
Allows the selection of one or more items from a list.
The built-int random
filter only allows you to select a single at a time, and repeated use can return the same item many times.
Example:
{% for random_item in item_list|several_random:3 %} ... {% endfor%}
Note: If you're running this on an uncached QuerySet, it can result in many database queries... a future improvement might check to see if the passed object is a QuerySet and act accordingly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import random as random_module
def several_random(value, arg=1):
"Returns one or more random item(s) from the list"
try:
arg = int(arg)
except ValueError:
return value
if arg == 1:
return random_module.choice(value)
elif len(value) > arg: # Only pick if we are asked for fewer items than we are given
return random_module.sample(value, arg)
else: # Number requested is equal to or greater than the number we have, return them all in random order
new_list = list(value)
random_module.shuffle(new_list)
return new_list
|
More like this
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 7 months, 4 weeks ago
- Crispy Form by sourabhsinha396 8 months, 3 weeks ago
- ReadOnlySelect by mkoistinen 9 months ago
- Verify events sent to your webhook endpoints by santos22 10 months ago
- Django Language Middleware by agusmakmun 10 months, 2 weeks ago
Comments
Please login first before commenting.