0

I have a modal that stores an integer number, user will be giving hexadecimal number and I am converting into integer and storing it in database, Now I need to expose my model through rest-api...by doing this user would be seeing integer value not hexadecimal, how can convert integer back to hexadecimal and show it to the user in rest-api?

Model:

class Address:
    base_addr = models.BigIntegerField(blank=False, null=False)

serializer:

class AddressSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Address
        fields = (base_addr,

)

viewset:

class AddressViewSet(viewsets.ReadOnlyModelViewSet):
    model = Address
    serializer_class = AddressSerializer
    filter_fields = ('base_addr')
    filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,)

1 Answer 1

2

Using serializers.SerializerMethodField

class Address:
    base_addr = models.BigIntegerField(blank=False, null=False)

    def get_hexadecimal(self):
        // your convertion logic here
        return addr_in_hexadecimal

then

class AddressSerializer(serializers.HyperlinkedModelSerializer):
    bae_addr_hex = serializers.Field(source='get_hexadecimal')
    class Meta:
        model = Address
        fields = ('bae_addr_hex', ...)
Sign up to request clarification or add additional context in comments.

4 Comments

How about you can't change your model? you just need to add a method
Thanks trinchet, One more small information if the user queries from rest-api like.. ?address = "0x5656576" How do I convert it back to interger and search in model. (Iam new to rest)
Before answer that, why you need to store Integers intead of the hexadecinal numbers? it seems you are overloading logic just for this
anyway you can see how filter/search here django-rest-framework.org/api-guide/…, an example here stackoverflow.com/a/21186065/1904584, hope that helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.