Login

several_random template filter

Author:
hawkeye
Posted:
May 11, 2007
Language:
Python
Version:
.96
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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.