python - 如何使用 django-autocomplete-light 更改选项值?

标签 python django autocomplete django-autocomplete-light

我以相当标准的方式使用 django-autocomplete-light,只需按照 http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html 上的教程进行操作即可.

然而,每当我使用 Select2 小部件时,选项的值都会自动成为模型实例的主键。有没有办法将值设置为模型的另一个字段?

最佳答案

只需要自己更改默认行为并遇到这个问题,希望它仍然可以帮助那里的人。

documentation提到了使用 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

现在要更改返回的 id,它非常相似。只需覆盖 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)

总的来说,我做了这样的事情:

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

关于python - 如何使用 django-autocomplete-light 更改选项值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870676/

相关文章:

javascript - 在javascript中循环遍历django列表

python - 将 pandas DataFrame 附加到具有固定标题的 csv

Python 多进程启动的进程多于内核

javascript - 当用户搜索某些内容时,如何使用 JavaScript 进行自动完成或建议?

python - Win10 : ImportError: DLL load failed: The specified module could not be found

django - 使用 django rest 框架和 django oauth 工具包在单元测试中进行 oAuth 身份验证

django - 操作错误 : no such table

python - 如何解决这个复杂的递归问题,金字塔点系统

emacs - Emacs 24 的自动完成不适用于 Java、C 或 C++ 模式

JQuery 自动完成仅适用于第一个输入