0

I'm trying to hide the id of my objects, but I don't know how to implement it in the correct way. What I did was this:

hashids = Hashids(settings.HASHIDS_SALT, min_length=32)

def parse_result(result) -> Union[int, None]:
    if result:
        if isinstance(result[0], int):
            return result[0]
        try:
            result = int(result[0])
            return result
        except Exception as error:
            print("Couldn't parse the decodification!")
            print(error)

def h_encode(id: int):
    return hashids.encode(id)


def h_decode(h: str) -> Union[int, None]:
    return parse_result(hashids.decode(h))

class HashIdField(serializers.CharField):
    def to_representation(self, value):
        value = h_encode(value)
        return super(HashIdField, self).to_representation(value)

    def to_internal_value(self, data):
        data = h_decode(data)
        return int(super(HashIdField, self).to_internal_value(data))

class ProducerSerializer(serializers.HyperlinkedModelSerializer):
    id = HashIdField(read_only=True)

    class Meta:
        model = Producer
        view_name = 'api:producer-detail'
        fields = (
            'id',
            'name',)

Although it works, I can still access the objects by their integer ID. Obs: I'm using viewset.

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
iaggo
  • 51
  • 5
  • Well, the view(set) is responsible for finding objects by the parameters in the URL, so editing the serializer won't help there. – AKX May 16 '22 at 20:05
  • So how do I edit the "view" to get a correct solution? I found a package that edits the serializer to get a similar solution. – iaggo May 17 '22 at 13:28
  • Depends on what your view(set) looks like. Hard to help without seeing it. – AKX May 17 '22 at 13:31

0 Answers0