Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter choices in Django2's autocomplete_fields?

Tags:

In Django 2.0, autocomplete_fields was added, which is great.

Without autocomplete_fields, I can change the queryset of a ForeignKeyField using formfield_for_foreignkey.

But combining the two together doesn't work - it looks like the list of options for autocomplete is dynamic and coming from a different url, instead of from the current form.

So the question is -

How can I change the queryset in the autocomplete widget?

like image 396
Oren Shpigel Avatar asked Jan 08 '18 15:01

Oren Shpigel


1 Answers

If you are using autocomplete_fields for a ManyToManyField on 'self', this example will exclude the current object.

Get the current object's id by overriding get_form:

field_for_autocomplete = None  def get_form(self, request, obj=None, **kwargs):     if obj:         self.field_for_autocomplete = obj.pk      return super(MyAdmin, self).get_form(request, obj, **kwargs) 

Next, override get_search_results. Modify the queryset only for your model's autocomplete URI:

def get_search_results(self, request, queryset, search_term):     queryset, use_distinct = super().get_search_results(request, queryset, search_term)      # Exclude only for autocomplete     if request.path == '/admin/myapp/mymodel/autocomplete/':         queryset = queryset.exclude(field=self.field_for_autocomplete)      return queryset, use_distinct 
like image 187
Mike Avatar answered Sep 18 '22 05:09

Mike