我以一种相当标准的方式使用django-autocomplete-light,只需遵循http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html上的教程。
但是,每当我使用Select2小部件时,选项的值都会自动成为模型实例的主键。有没有一种方法可以将值设置为模型的另一个字段?
发布于 2018-12-11 09:47:24
只是我自己需要改变默认行为,然后遇到了这个问题,希望它仍然能帮助到一些人。
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 qshttps://stackoverflow.com/questions/47870676
复制相似问题