Yves Wehrli Yves Wehrli - 2 months ago 26
Python Question

Django - Filter QuerySet only in admin-list and not in admin detail page

In the Django admin list view, i want to hide products without a name. I just excluded them in the get_query_set() method.

def get_queryset(self, request):
qs = super(ProductAdmin, self).get_queryset(request)
return qs.exclude(name=None)

This is working perfect, but i want to be able to access products without a name in the admin detail page (with a direct link).
When it try this, i have an error, because it filters the product out of the queryset:

product object with primary key u'123' does not exist.

Is there a workaround for this problem? If possible, without adding a custom filter to the list view.


Well, you could override get_object

def get_object(self, request, object_id, from_field=None):
    Returns an instance matching the field and value provided, the primary
    key is used if no field is provided. Returns ``None`` if no match is
    found or the object_id fails validation.

    model = product
    field = model._meta.pk if from_field is None else model._meta.get_field(from_field)
        object_id = field.to_python(object_id)
        return model.objects.get(**{field.name: object_id})
    except (model.DoesNotExist, ValidationError, ValueError):
        return None

This is undocumented but can be made to work. The standard way though is to use a custom filter.