1👍
✅
In your class:
class Character(models.Model):
name = models.CharField(primary_key=True, max_length=10)
level = models.IntegerField(blank=True, null=True)
class_name= models.SmallIntegerField(blank=True, null=True)
pk_count = models.IntegerField(blank=True, null=True)
resets = models.SmallIntegerField(blank=True, null=True)
#add a dict for your values
values = {'1':'Warrior','2':'Whatever'}
@property
def class_name_value(self):
return values[self.class_name] if values[self.class_name] else 'default'
And then your serializer:
class CharacterSerializer(serializers.ModelSerializer):
class Meta:
model = models.Character
fields = ('name', 'level', 'class_name_value', 'pk_count', 'resets')
1👍
dmitryro’s answer is a good way to easily get access to those mapped values anywhere in the site. Another way to map a value to the field name, only within the serializer in question, would be to use a SerializerMethodField
class CharacterSerializer(serializers.ModelSerializer):
class_name = serializers.SerializerMethodField()
class Meta:
model = models.Character
fields = ('name', 'level', 'class_name', 'pk_count', 'resets')
def get_class_name(self, obj):
try:
return obj.values[str(obj.class_name)]
except KeyError:
return 'default'
Source:stackexchange.com