Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass choice display name to model serialize in Django REST framework?

My env is Django 2.0.3, DRF 3.8.2 and Python 3.6.4.

I have a model in serializers.py:

class TransferCostSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        field_view = super().to_representation(instance)
        if field_view['is_active']:
            return field_view
        return None

    class Meta:
        model = TransferCost
        fields = ('id', 'destination', 'total_cost', 'is_active',)

Where destination field is choice field of 3 elements:

DESTINATION = (
    ('none', _('I will drive by myself')),
    ('transfer_airport', _('Only from airport')),
    ('transfer_round_trip', _('Round trip')),
)

This is my models.py:

class TransferCost(models.Model):

    destination = models.CharField(
        _('Transfer Destination'), choices=DESTINATION, max_length=55
    )
    total_cost = models.PositiveIntegerField(
        _('Total cost'), default=0
    )
    is_active = models.BooleanField(_('Transfer active?'), default=True)

    class Meta:
        verbose_name = _('Transfer')
        verbose_name_plural = _('Transfers')

    def __str__(self):
        return _('Transfer {}').format(self.destination)

..And I return JSON like this:

[
    {
        id: 1,
        destination: "transfer_airport",
        total_cost: 25,
        is_active: true
    },
    {
        id: 2,
        destination: "transfer_round_trip",
        total_cost: 45,
        is_active: true
    }
]

How to return destination field with his display name? For example:

[
    {
        id: 1,
        destination_display: "Only from airport",
        destination: "transfer_round_trip",
        total_cost: 25,
        is_active: true
    },
    {
        id: 2,
        destination_display: "Round trip",
        destination: "transfer_round_trip",
        total_cost: 45,
        is_active: true
    }
]

Would be great to have something like get_FOO_display() in serializers.py, but it's not working. I need this thing, because I render form dynamically via Vue.js (as v-for select list).

like image 386
koddr Avatar asked May 15 '18 07:05

koddr


People also ask

How do you serialize an object list in Django REST framework?

Serializing objects We can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class. At this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into json .

How do you pass extra context data to Serializers in Django REST framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is Serializers in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


2 Answers

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',)
like image 119
hadi ahadi Avatar answered Oct 09 '22 15:10

hadi ahadi


you can use fields source with get_FOO_display

class TransferCostSerializer(serializers.ModelSerializer):
    destination_display = serializers.CharField(
        source='get_destination_display'
    )
like image 27
Brown Bear Avatar answered Oct 09 '22 14:10

Brown Bear