Skip to content

Commit 4015834

Browse files
authored
proper handle get_choices for DRF browsable api
1 parent d014754 commit 4015834

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

ckc/fields.py

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,29 @@ def __init__(self, *args, **kwargs):
1515
def use_pk_only_optimization(self):
1616
return False
1717

18-
def to_representation(self, value):
19-
# Are we on the browsable API? if so, just return pk!
20-
if self.context['request'].META["HTTP_ACCEPT"].startswith("text/html"):
18+
def to_representation(self, value, pk_only=False):
19+
if pk_only:
20+
# Returning just the PK so dropdowns can render this as an option in DRF browsable API
2121
return value.pk
2222
else:
23-
# Normal request, return full item read details
23+
# Returning full dict representation for reading normally
2424
return self.read_serializer(value, context=self.context).data
25+
26+
def get_choices(self, cutoff=None):
27+
"""Overriding this base method to change to_representation so it passes pk_only=True"""
28+
queryset = self.get_queryset()
29+
if queryset is None:
30+
# Ensure that field.choices returns something sensible
31+
# even when accessed with a read-only field.
32+
return {}
33+
34+
if cutoff is not None:
35+
queryset = queryset[:cutoff]
36+
37+
return OrderedDict([
38+
(
39+
self.to_representation(item, pk_only=True),
40+
self.display_value(item)
41+
)
42+
for item in queryset
43+
])

0 commit comments

Comments
 (0)