[Django]-How I can get related model for custom column in admin list_display with prefetch_related?

4👍

The problem is that you are filtering the prefetched results with filter(num=1). This causes Django to do a new query.

You can use a Prefetch object to fetch the correct queryset. Note you should override the model admin’s get_queryset method, not queryset.

def get_queryset(self, request):
    return super(GroupAdmin,self).get_queryset(request).prefetch_related(
        Prefetch('hotel_details', queryset=HotelDetails.objects.filter(num=1).select_related('hotel'), to_attr='hotel_details_num1'),
    )

Then change your model admin methods to use the new queryset, for example:

def first_hotel(self, instance):
    return instance.hotel_details_num1.first().hotel

See the docs for more into about prefetch_related and Prefetch objects.

Leave a comment