我有一个存储整数的模态,用户将给出十六进制数,我将转换为整数并将其存储在数据库中,现在我需要通过rest-api公开我的模型...通过这个用户将看到整数值不是十六进制,如何将整数转换回十六进制并在rest-api中显示给用户?
型号:
class Address:
base_addr = models.BigIntegerField(blank=False, null=False)
串行器:
class AddressSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Address
fields = (base_addr,
)
视图集:
class AddressViewSet(viewsets.ReadOnlyModelViewSet):
model = Address
serializer_class = AddressSerializer
filter_fields = ('base_addr')
filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,)
答案 0 :(得分:2)
使用serializers.SerializerMethodField
class Address:
base_addr = models.BigIntegerField(blank=False, null=False)
def get_hexadecimal(self):
// your convertion logic here
return addr_in_hexadecimal
然后
class AddressSerializer(serializers.HyperlinkedModelSerializer):
bae_addr_hex = serializers.Field(source='get_hexadecimal')
class Meta:
model = Address
fields = ('bae_addr_hex', ...)