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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.