Login

several_random template filter

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

  1. Pagination/Filtering Alphabetically by zain 6 years, 4 months ago
  2. Allow filtering and ordering by counts of related query results by exogen 8 years, 3 months ago
  3. Batch querysets by jkocherhans 6 years, 8 months ago
  4. MultiSelect checkbox iterator template filter by ke1g 4 years, 11 months ago
  5. Admin list_display Ajax by whiteinge 7 years, 6 months ago

Comments

Please login first before commenting.