Django:values_list()多个字段连接 [英] Django: values_list() multiple fields concatenated
问题描述
Person
模型,而我正在使用一个django表单来编辑一个外键的另一个对象 Person
。人物模型具有 first_name
和 last_name
字段。我想运行一个方法来过滤外部引用的下拉框的结果。 我正在尝试使用 values_list()
覆盖表单域选项(choice属性),如下所示:
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
而不必返回一个字典并手动拆分所有的东西
/ p>
- 首先是将数据库中的字段与 extra 。对我来说是一个肮脏的解决方案,但可以运行。
示例:
persons = GetPersons()。extra(select = {'full_name':concatenate(first,last)})
choices = persons.values_list('id','full_name ')
和...
- 第二个使用列表理解:
示例:
$ b $在GetPersons()中,p
p = $(p.id,'{0} {1}'。format(p.first,p.last) b $ b
I have a Person
model and I am using a django form to edit another object with a foreign key to Person
. The person model has first_name
and last_name
fields. I want to run a method to filter results for the drop down box of the foreign reference.
I am trying to use values_list()
to override the form field options (choices property) like so:
data.form.fields['person'].choices = GetPersons().values_list('id', 'first_name')
GetPersons()
just filters the Person class like
return Person.objects.filter(id__gt=1000)`
for example, so I only get people I want to show up. How can I use values_list()
to return the concatenation of first_name
and last_name
without having to return a dictionary and splitting everything manually?
I have in mind 2 sugestions for you:
- First one is to concatenate fields in database with extra . For me is a dirty solutions but can run.
Sample:
persons = GetPersons().extra(select={'full_name': "concatenate( first, last) "} )
choices = persons.values_list('id', 'full_name')
and ...
- the second one use list comprehension:
Sample:
choices = [ ( p.id, '{0} {1}'.format( p.first, p.last ),) for p in GetPersons() ]
这篇关于Django:values_list()多个字段连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!