From 381c81a8ffac8c4b3abf6a762d031a7e261e8eaa Mon Sep 17 00:00:00 2001 From: Matthijs Kooijman Date: Tue, 10 Feb 2009 19:48:05 +0100 Subject: [PATCH] Add filter_choices helper function. This function allows to easily filter choices for model fields, without duplicating descriptions. --- tools/misc.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tools/misc.py b/tools/misc.py index 2c78548..ddc6cee 100644 --- a/tools/misc.py +++ b/tools/misc.py @@ -40,3 +40,20 @@ def make_choices(objects): FormField and is not public. """ return [(o.pk, o) for o in objects] + +def filter_choices(choices, filter): + """ + Returns the given choices list with only the choices with the names + in filter left. For example, when a model defines + A = 'A' + B = 'B' + FOO_CHOICES = ( + (A, "Foo A"), + (B, "Foo B") + ) + + you can later define a modelfield using + + foo = ChoiceField(choices=filter_choices(Foo.FOO_CHOICES, [Foo.A])) + """ + return [(name, value) for (name, value) in choices if name in filter] -- 2.30.2