django-hashids icon indicating copy to clipboard operation
django-hashids copied to clipboard

How do I change the default lookup field in the admin

Open danihodovic opened this issue 3 years ago • 4 comments

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/ links to a product change page?

danihodovic avatar Jun 29 '22 15:06 danihodovic

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?

ericls avatar Jul 01 '22 20:07 ericls

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 avatar Jul 01 '22 20:07 danihodovic

@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?

ericls avatar Jul 03 '22 03:07 ericls

I'll create a PR to include it in the docs.

danihodovic avatar Jul 03 '22 11:07 danihodovic