Search code examples
djangodjango-autocomplete-light

Django Autocomplete Light doesn't return result until process restart


When I add a new record in the database, it doesn't appear in the autocomplete results until I restart the python process. My registry looks like this.

    import autocomplete_light

    from .models import Article


    autocomplete_light.register(
        Article,

        choices=Article.objects.published(),

        search_fields=['title', '^id', ],

        attrs={
            'placeholder': 'Search by Article Name',
        },
        widget_attrs={
            'class': 'modern-style',
        },
    )

Is the choices option cached?


Solution

  • I ended up using a class for the registry and setting the request_choices instead of the method above.

    import autocomplete_light
    
    from apps.abstract.models import PUBLISHED
    from .models import Article
    
    
    class ArticleAutocomplete(autocomplete_light.AutocompleteModelBase):
        attrs = {
            'placeholder': 'Search by Article Title',
        }
        search_fields = ['title', '^id', ]
        widget_attrs = {
            'class': 'modern-style',
        }
    
        def choices_for_request(self):
            """Returns published articles for the request"""
            self.choices = self.choices.filter(status=PUBLISHED)
            return super(ArticleAutocomplete, self).choices_for_request()
    
    autocomplete_light.register(Article, ArticleAutocomplete)