django-hashids
django-hashids copied to clipboard
How do I change the default lookup field in the admin
Using DRF and changing the lookup field is easy
class ProductViewSet(viewsets.ModelViewSet):
lookup_field = "hashid"
# ...
How do I do the same within admin so that http://localhost:8000/admin/core/product/
Hi @danihodovic , sorry but I'm not aware of a simple way to do this in Django admin. Looks like Django admin would always use the primary key to identify objects. May I ask what's your use case for this? Is it you want the hashid instead of real id to show up in the URL?
Is it you want the hashid instead of real id to show up in the URL?
Correct
I managed to hack around this by overriding some of the admin.ModelAdmin methods:
class ModelAdmin(admin.ModelAdmin):
"""
Filtering fields via hashid in the admin url.
"""
def get_changelist_instance(self, request):
instance = super().get_changelist_instance(request)
instance.pk_attname = "hashid"
return instance
def get_object(self, request, object_id, from_field=None):
return super().get_object(request, object_id, from_field="hashid")
FWIW I also use the following classes to make usage via DRF easier:
class ModelViewSet(viewsets.ModelViewSet):
lookup_field = "hashid"
lookup_url_kwarg = "pk"
class ModelSerializer(serializers.ModelSerializer):
id = serializers.CharField(source="hashid", read_only=True)
@danihodovic , Thanks for providing the workaround. Do you want to close this issue or do you think we should include the snippet in the docs or somewhere in the code?
I'll create a PR to include it in the docs.