Skip to content

Commit

Permalink
proper handle get_choices for DRF browsable api
Browse files Browse the repository at this point in the history
  • Loading branch information
ckcollab authored Mar 18, 2022
1 parent d014754 commit 4015834
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions ckc/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,29 @@ def __init__(self, *args, **kwargs):
def use_pk_only_optimization(self):
return False

def to_representation(self, value):
# Are we on the browsable API? if so, just return pk!
if self.context['request'].META["HTTP_ACCEPT"].startswith("text/html"):
def to_representation(self, value, pk_only=False):
if pk_only:
# Returning just the PK so dropdowns can render this as an option in DRF browsable API
return value.pk
else:
# Normal request, return full item read details
# Returning full dict representation for reading normally
return self.read_serializer(value, context=self.context).data

def get_choices(self, cutoff=None):
"""Overriding this base method to change to_representation so it passes pk_only=True"""
queryset = self.get_queryset()
if queryset is None:
# Ensure that field.choices returns something sensible
# even when accessed with a read-only field.
return {}

if cutoff is not None:
queryset = queryset[:cutoff]

return OrderedDict([
(
self.to_representation(item, pk_only=True),
self.display_value(item)
)
for item in queryset
])

0 comments on commit 4015834

Please sign in to comment.