Search code examples
pythondjangoautocompletedjango-autocomplete-light

How to change the option values with django-autocomplete-light?


I use django-autocomplete-light in a fairly standard way, simply following the tutorial on http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html.

Whenever I use the Select2 widget, however, the values of the options are automatically the primary keys of the model instances. Is there a way to use set the value to another field of the model?


Solution

  • Just needed to change the default behavior myself and ran into this, hope it's still going to help someone out there.

    The documentation mentioned the way to return different labels using get_result_label

    class CountryAutocomplete(autocomplete.Select2QuerySetView):
        def get_result_label(self, item):
            return item.full_name
    
        def get_selected_result_label(self, item):
            return item.short_name
    

    Now to alter the returned id's, it's very similar. Just overwrite get_result_value:

    def get_result_value(self, result):
        """
        this below is the default behavior, 
        change it to whatever you want returned
        """
        return str(result.pk)
    

    In summary, I did something like this:

    class TagAutocomplete(autocomplete.Select2QuerySetView):
    
        def get_result_value(self, result):
            return str(result.name)
    
        def get_queryset(self):
            qs = Tag.objects.all()
            if self.q:
                q = self.q
                qs = qs.filter(
                            Q(name__icontains=q)
                        )
            return qs