擅长:python、mysql、java
<p><a href="https://stackoverflow.com/a/62702793/5900093">Ananya's answer</a>帮助我正确地理解了该语句返回的内容,但是在考虑了错误以及选择列表通常是如何构造的之后,我意识到我需要它来返回元组(而不仅仅是值)。以下是最终有效的相关代码:</p>
<pre><code>class office_filter(django_filters.FilterSet):
supervisor = django_filters.ChoiceFilter(choices=[], label='Supervisor')
#...
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
self.filters['supervisor'].extra['choices'] = [(people.objects.get(pk=x).id, people.objects.get(pk=x)) for x in people.objects.all().values_list('supervisor', flat=True).distinct() if x is not None]
except (KeyError, AttributeError):
pass
</code></pre>
<p>重要的部分是:<code>(people.objects.get(pk=x).id, people.objects.get(pk=x))</code>,而不仅仅是<code>people.objects.get(pk=x)</code></p>
<p>还必须删除筛选器字段中的<code>lookup_expr</code></p>