nshafer / django-hashid-field

Django Model Field that uses Hashids to obscure the value
MIT License
370 stars 40 forks source link

Add option to encode when reading #75

Closed ThomasAitken closed 7 months ago

ThomasAitken commented 2 years ago

This is an issue that has come up in the context of temporarily saving a form to the backend in JSON format. Any ids using HashSerializerCharField for the write request get saved in the backend as integer ids. Then, when we want to retrieve that form data, the data comes back in a decoded format (the ids are converted to strings but not converted back into hashed ids as desired). There should be an extra option for the HashidSerializerCharField called encode_on_read to handle this. Currently, I am handling by overriding the default to_representation method myself.

nshafer commented 2 years ago

Can you provide me with a way to duplicate the problem, or a failing test that illustrates it? Or perhaps your custom to_representation? However, it does sound like you're doing something specialized, which would call for a specialized serializer field either way.

ThomasAitken commented 2 years ago

This is my custom to_representation.

    def to_representation(self, value):
        if isinstance(value, int):
            hashids = Hashids(salt=settings.HASHID_FIELD_SALT, min_length=7)
            return hashids.encode(value)
        return super().to_representation(value)

It may be a specialized case but I imagine that it wouldn't be completely unique. An alternative would have been to use a simple CharField for this use case, so that we send the hashed id to the backend and get it back in the same format. Unfortunately, since we didn't use this from the start, we now have to do this encoding on read to get existing saved data back in the correct format.