Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter autocompletion results in django grappelli?

We have a soft delete scheme where we just mark things as deleted and then filter the deleted ones out in various places. I'm trying to figure out how to filter the deleted ones out of the grapelli autocomplete suggestions.

like image 759
Gordon Wrigley Avatar asked Jul 25 '13 08:07

Gordon Wrigley


2 Answers

In the end I went with this:

from grappelli.views.related import AutocompleteLookup

class YPAutocompleteLookup(AutocompleteLookup):
    """ patch grappelli's autocomplete to let us control the queryset 
    by creating a autocomplete_queryset function on the model """
    def get_queryset(self):
        if hasattr(self.model, "autocomplete_queryset"):
            qs = self.model.autocomplete_queryset()
        else:
            qs = self.model._default_manager.all()
        qs = self.get_filtered_queryset(qs)
        qs = self.get_searched_queryset(qs)
        return qs.distinct()

It can be installed by overriding the relevant url:

url(r'^grappelli/lookup/autocomplete/$', YPAutocompleteLookup.as_view(), name="grp_autocomplete_lookup"),

Make sure this is ahead of Grappelli in your urls.

like image 76
Gordon Wrigley Avatar answered Nov 03 '22 16:11

Gordon Wrigley


If your working with the Admin site, you should take advantage of the ModelAdmin.queryset function: https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#django.contrib.admin.ModelAdmin.queryset

As I found out, changing the default model manager to restrict the results is a bad idea, causing all kinds of nasty problems. For example: preventing syncdb, shell or shell_plus from running. Making it impossible to add the first record to a blank db. The exact errors depend upon what your restricting, but you are bound to get a few.

What is needed here is a way to tell Grappelli the name of the queryset manager to use. Passed in or a setting perhaps?

You can specify a simple (constant or related field) filter using ForeignKey.limit_choices_to. Grappelli grabs this value and sends it in the GET as param 'query_string'.

However, this might not be enough. I posted a request to the Grappelli repo I use to add a way to specify the record manger to use, or just automatically use the admin queryset (ModelAdmin.queryset).

My post is here: https://github.com/sehmaschine/django-grappelli/issues/362

like image 1
Richard Cooke Avatar answered Nov 03 '22 14:11

Richard Cooke