nshafer / django-hashid-field

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

Not clear on how to serialize a ForeignKey to a model using HashidAutoField #4

Closed pembo13 closed 7 years ago

pembo13 commented 7 years ago

I was getting serialization errors as the serialize didn't know how to serialize the foreign models PK.

As a temporary workaround, I did this, but I suspect it's not the best way:

class HashidSerializerRelatedField(serializers.RelatedField):

    def to_representation(self, value):
        return str(value.id)

    pass
nshafer commented 7 years ago

Thanks for bringing this up, I hadn't given it any thought and hadn't run across it myself. After reading through DRF's docs and playing around with an example situation in my sandbox, I think the best solution is to continue to use DRF's PrimaryKeyRelatedField, and just tell it to use the HashidSerializer*Field you want to use by setting its pk_field attribute. I just updated the docs with more information that will hopefully explain it. You can also see some examples in sandbox/library/serializers.py. Hope that helps!

nshafer commented 7 years ago

BTW, I'll keep this issue open for now. Let me know if that works for you or not in your situation.

pembo13 commented 7 years ago

That works perfectly, and thanks for updating the docs.