How to filter ModelAdmin autocomplete_fields results with the context of limit_choices_to
14:25 25 Mar 2019

I have a situation where I wish to utilize Django's autocomplete admin widget, that respects a referencing models field limitation.

For example I have the following Collection model that has the attribute kind with specified choices.

class Collection(models.Model):
    ...
    COLLECTION_KINDS = (
        ('personal', 'Personal'),
        ('collaborative', 'Collaborative'),
    )

    name = models.CharField()
    kind = models.CharField(choices=COLLECTION_KINDS)
    ...

Another model ScheduledCollection references Collection with a ForeignKey field that implements limit_choices_to option. The purpose of this model is to associate meta data to a Collection for a specific use case.

class ScheduledCollection(models.Model):
    ...
    collection = models.ForeignKey(Collection, limit_choices_to={'kind': 'collaborative'})

    start_date = models.DateField()
    end_date = models.DateField()
    ...

Both models are registered with a ModelAdmin. The Collection model implements search_fields.

@register(models.Collection)
class CollectionAdmin(ModelAdmin):
    ...
    search_fields = ['name']
    ...

The ScheduledCollection model implements autocomplete_fields

@register(models.ScheduledCollection)
class ScheduledCollectionAdmin(ModelAdmin):
    ...
    autocomplete_fields = ['collection']
    ...

This works but not entirely as expected. The autocomplete retrieves results from a view generated by the Collection model. The limit_choices_to do not filter the results and are only enforced upon save.

It has been suggested to implement get_search_results or get_queryset on the CollectionAdmin model. I was able to do this and filter the results. However, this changes Collection search results across the board. I am unaware of how to attain more context within get_search_results or get_queryset to conditionally filter the results based upon a relationship.

In my case I would like to have several choices for Collection and several meta models with different limit_choices_to options and have the autocomplete feature respect these restrictions.

I don't expect this to work automagically and maybe this should be a feature request. At this point I am at a loss how to filter the results of a autocomplete with the respect to a choice limitation (or any condition).

Without using autocomplete_fields the Django admin's default