2

I'm using django autocomplete_light for a model search, but would like something different to the model's default string (i.e. __unicode__()) being shown in the autocompleted results. Is this possible?

askvictor
  • 3,621
  • 4
  • 32
  • 45

3 Answers3

0

Yes, use autocompleteListBase

class your_autocomplete_class(autocomplete_light.AutocompleteListBase):

names= model_name.objects.values_list('user__email', flat=True)
choices = [v for v in names]

autocomplete_light.register(your_autocomplete_class)
0

Yes, by overriding choice_label and return the value to display for a choice.

Example

class BookAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['title']
    model = Book

    def choice_label(self, choice):
        return '"{0.title}" by {0.author}'.format(choice)
phoibos
  • 3,900
  • 2
  • 26
  • 26
0

You can override the get_result_label method form the BaseQuerySetView.

(In the following example, Select2QuerySetView inherits from BaseQuerySetView)

class MyModelAutocompleteView(autocomplete.Select2QuerySetView):

    def get_queryset(self)
        return MyModel.objects.filter(name__icontains='foo')

    def get_result_label(self, result):
        return '{0} is a choice'.format(result)
vmonteco
  • 14,136
  • 15
  • 55
  • 86