我有一个Person
模型,我正在使用 django 表单来编辑另一个带有外键的对象Person
。人物模型有first_name
and 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
and last_name
无需返回字典并手动拆分所有内容?
我心里有两条建议给你:
- 第一个是将数据库中的字段与extra https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra。对我来说是一个肮脏的解决方案但可以运行。
Sample:
persons = GetPersons().extra(select={'full_name': "concatenate( first, last) "} )
choices = persons.values_list('id', 'full_name')
and ...
Sample:
choices = [ ( p.id, '{0} {1}'.format( p.first, p.last ),) for p in GetPersons() ]
2018年编辑
Concat https://docs.djangoproject.com/en/2.1/ref/models/database-functions/#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()
... )
... )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)