Add filter_choices helper function.
authorMatthijs Kooijman <matthijs@stdin.nl>
Tue, 10 Feb 2009 18:48:05 +0000 (19:48 +0100)
committerMatthijs Kooijman <matthijs@stdin.nl>
Tue, 10 Feb 2009 18:48:05 +0000 (19:48 +0100)
This function allows to easily filter choices for model fields, without
duplicating descriptions.

tools/misc.py

index 2c785482e5a9e1da735a4d05c3b75ec41b78493b..ddc6cee7490dc6fc3492376f5e004821827b2952 100644 (file)
@@ -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]