How to filter choices in Django2's autocomplet

2019-03-20 23:00发布

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?

1条回答
仙女界的扛把子
2楼-- · 2019-03-20 23:33

Override the ModelAdmin's get_search_results method to use the query you want. You can see in the get_queryset method for the view providing the data for autocomplete fields that it's used to get the queryset - the source as of this answer is https://github.com/django/django/blob/master/django/contrib/admin/views/autocomplete.py#L42 but I do not expect that link to say correct over time.

查看更多
登录 后发表回答