1
- import operator
2
1
import typing
3
2
4
3
from django .conf import settings
@@ -21,6 +20,7 @@ def from_model(
21
20
no_limit = True ,
22
21
context_fields : typing .List [str ] = None ,
23
22
select_related : typing .List [str ] = None ,
23
+ allow_undefined_context = False ,
24
24
) -> typing .Tuple [typing .List [types .DropdownItem ], int ]:
25
25
"""
26
26
Get dropdown items from given model
@@ -32,6 +32,7 @@ def from_model(
32
32
@param no_limit: no items limit (overriding `LIMIT` in settings)
33
33
@param context_fields: additional fields to be appear in context in each dropdown item
34
34
@param select_related: fields to select related
35
+ @param allow_undefined_context: allow any context field to be None if there is no attribute
35
36
@return: tuple of dropdown items and item count
36
37
"""
37
38
if context_fields is None :
@@ -76,9 +77,9 @@ def from_model(
76
77
# results
77
78
return utils .remove_duplication (
78
79
types .DropdownItem (
79
- label = operator .attrgetter (label_field )( x ) if label_field is not None else str (x ),
80
- value = operator .attrgetter (value_field )( x ),
81
- context = {y : operator .attrgetter (y )( x ) for y in (context_fields )},
80
+ label = utils .attrgetter (x , label_field ) if label_field is not None else str (x ),
81
+ value = utils .attrgetter (x , value_field ),
82
+ context = {y : utils .attrgetter (x , y , raise_exception = not allow_undefined_context ) for y in (context_fields )},
82
83
) for x in result_list
83
84
), count
84
85
0 commit comments