'Django Model verbose_name as API rows response names

As I can't save special characters in fields in django model I have to bypass it. For example: I would like to have "km/h" field. So I'm using it like:

class Unit(models.Model):
    kmh = models.FloatField(null=True, db_column='km/h', verbose_name='km/h')

then I have example serializer:

class UnitSerializer(serializers.ModelSerializer):
     class Meta:
        model = Unit
        fields = ['kmh']

and when I'll use it with APIViews response which will include the field will look like:

{
   "kmh":10,
}

I would like to make it look like my verbose_name so:

{
 "km/h":10
}

How can I do it? I have like 30 of these fields with special characters.



Solution 1:[1]

You can define field names with special characters by updating the locals() but I would strongly advise not to do this: in both Python and JavaScript, variable names with spaces make it less convenient to retrieve attributes, update data, etc. In most programming languages and frameworks, this can only make it worse to process the data.

You can define a field, and specify the source=… parameter to specify where to retrieve the data from:

class UnitSerializer(serializers.ModelSerializer):
    locals().update({
        'km/h': serializers.FloatField(source='kmh', allow_null=True)
    })
    
    class Meta:
        model = Unit
        fields = ['km/h']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1