Skip to content

Commit 31c09a7

Browse files
authored
Merge pull request #9 from earthpyy/allow-none-context
Allow undefined context
2 parents ae3157e + 99a8e99 commit 31c09a7

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

dropdown/helpers.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import operator
21
import typing
32

43
from django.conf import settings
@@ -21,6 +20,7 @@ def from_model(
2120
no_limit=True,
2221
context_fields: typing.List[str] = None,
2322
select_related: typing.List[str] = None,
23+
allow_undefined_context=False,
2424
) -> typing.Tuple[typing.List[types.DropdownItem], int]:
2525
"""
2626
Get dropdown items from given model
@@ -32,6 +32,7 @@ def from_model(
3232
@param no_limit: no items limit (overriding `LIMIT` in settings)
3333
@param context_fields: additional fields to be appear in context in each dropdown item
3434
@param select_related: fields to select related
35+
@param allow_undefined_context: allow any context field to be None if there is no attribute
3536
@return: tuple of dropdown items and item count
3637
"""
3738
if context_fields is None:
@@ -76,9 +77,9 @@ def from_model(
7677
# results
7778
return utils.remove_duplication(
7879
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)},
8283
) for x in result_list
8384
), count
8485

dropdown/utils.py

+11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import collections
2+
import operator
23
import typing
34

45

@@ -8,3 +9,13 @@ def dot_to_relation(value: str) -> str:
89

910
def remove_duplication(value: typing.Iterable) -> list:
1011
return list(collections.OrderedDict.fromkeys(value))
12+
13+
14+
def attrgetter(obj: dict, key: str, raise_exception=True, default=None):
15+
try:
16+
return operator.attrgetter(key)(obj)
17+
except AttributeError:
18+
if raise_exception:
19+
raise
20+
21+
return default

0 commit comments

Comments
 (0)