How to filter autocomplete results in django grappelli?

We have a soft deletion scheme where we simply mark things as deleted and then filter the deleted in different places. I am trying to figure out how to filter out grapelli autofill suggestions that are deleted.

+6
source share
3 answers

In the end, I went with this:

from grappelli.views.related import AutocompleteLookup class YPAutocompleteLookup(AutocompleteLookup): """ patch grappelli 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 set by overriding the corresponding URL:

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

Make sure it’s ahead of Grappelli in your URLs.

+6
source

If you are working with the Admin website, you should use 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 limit results is a bad idea that causes all kinds of nasty problems. For example: preventing syncdb, shell, or shell_plus from starting. Unable to add first record to empty db. Exact errors depend on what you are limiting, but you must get a few.

Here you must specify how Grappelli uses the name of the query manager. Perhaps missed or installed?

You can specify a simple (permanent or related) filter using ForeignKey.limit_choices_to. Grappelli captures this value and sends it to GET as param 'query_string'.

However, this may not be enough. I sent a request to the Grappelli repository, which I use to add a way to specify the mailbox to use for writing, or just use the admin request (ModelAdmin.queryset).

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

+1
source

It looks like you can somehow pass additional search parameters into ajax autocomplete. An interface hack is probably needed.

https://github.com/sehmaschine/django-grappelli/blob/master/grappelli/views/related.py#L101

OR

You can force the Default Dispatcher for models to return an already filtered list and have places that explicitly deleted items should be removed to remove this restriction.

This is likely to make the default choice a lot easier for you in all directions.

0
source

Source: https://habr.com/ru/post/950232/


All Articles