我有一个 Person
模型,我正在使用 django 表单来编辑另一个具有 Person
外键的对象.人物模型有first_name
和 last_name
字段。我想运行一种方法来过滤外部引用下拉框的结果。
我正在尝试使用 values_list()
像这样覆盖表单字段选项(选择属性):
data.form.fields['person'].choices = GetPersons().values_list('id', 'first_name')
GetPersons()
只过滤 Person 类return Person.objects.filter(id__gt=1000)`
例如,所以我只让我想出现的人出现。如何使用
values_list()
返回 first_name
的串联和 last_name
无需返回字典并手动拆分所有内容?
最佳答案
我有两个建议给你:
样本:
persons = GetPersons().extra(select={'full_name': "concatenate( first, last) "} )
choices = persons.values_list('id', 'full_name')
和 ...
样本:
choices = [ ( p.id, '{0} {1}'.format( p.first, p.last ),) for p in GetPersons() ]
2018 年编辑
Concat现在可用作数据库功能:
>>> from django.db.models import CharField, Value as V
>>> from django.db.models.functions import Concat
>>> persons = GetPersons().annotate(
... full_name=Concat(
... 'last', V(', '), 'first', V('.'),
... output_field=CharField()
... )
... )
关于Django:values_list() 连接多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11417673/