34👍
✅
you can use fields source with get_FOO_display
class TransferCostSerializer(serializers.ModelSerializer):
destination_display = serializers.CharField(
source='get_destination_display'
)
3👍
just place get_destination_display
withoput ()
in fields
. like this:
class TransferCostSerializer(serializers.ModelSerializer):
class Meta:
model = TransferCost
fields = ('id', 'get_destination_display', 'total_cost', 'is_active',)
- Django – Objects for business hours
- How to find top-X highest values in column using Django Queryset without cutting off ties at the bottom?
- Django: use render_to_response and set cookie
- Django Authentication Mongodb
0👍
In case you want to have the values of all model fields with choices to be returned as display values, following worked out for me:
from rest_framework import serializers
from django.core.exceptions import FieldDoesNotExist
class TransferCostSerializer(serializers.ModelSerializer):
class Meta:
model = TransferCost
fields = ('id', 'destination', 'total_cost', 'is_active',)
def to_representation(self, instance):
"""
Overwrites choices fields to return their display value instead of their value.
"""
data = super().to_representation(instance)
for field in data:
try:
if instance._meta.get_field(field).choices:
data[field] = getattr(instance, "get_" + field + "_display")()
except FieldDoesNotExist:
pass
return data
The other solutions dropped auto generated meta-information of the model fields, e.g., translated labels.
- Celery and signals
- Django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited
- Getting "OSError: dlopen() failed to load a library: cairo / cairo-2" on Windows
Source:stackexchange.com