【问题标题】:Can django autocomplete_light show something than the model's string representation?django autocomplete light 可以显示模型字符串表示之外的东西吗?
【发布时间】:2014-10-06 23:12:34
【问题描述】:

我正在使用 django autocomplete_light 进行模型搜索,但希望在自动完成的结果中显示与模型的默认字符串(即__unicode__())不同的内容。这可能吗?

【问题讨论】:

    标签: django django-autocomplete-light


    【解决方案1】:

    是的,使用 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)
    

    【讨论】:

      【解决方案2】:

      ,通过覆盖 choice_label 并返回要显示的值以供选择。

      示例

      class BookAutocomplete(autocomplete_light.AutocompleteModelBase):
          search_fields = ['title']
          model = Book
      
          def choice_label(self, choice):
              return '"{0.title}" by {0.author}'.format(choice)
      

      【讨论】:

        【解决方案3】:

        您可以覆盖 BaseQuerySetView 中的 get_result_label 方法。

        (在以下示例中,Select2QuerySetView 继承自 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)
        

        【讨论】:

          猜你喜欢
          • 2018-09-29
          • 2021-06-14
          • 2016-10-21
          • 2016-10-12
          • 1970-01-01
          • 1970-01-01
          • 2017-03-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多