Yves Wehrli Yves Wehrli - 1 month ago 16
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:
http://127.0.0.1/product/123


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.

Answer

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)
    try:
        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.