Django: values_list() multiple fields concatenated

后端 未结 3 884
予麋鹿
予麋鹿 2021-02-19 02:16

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 an

3条回答
  •  太阳男子
    2021-02-19 02:45

    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() ]
    

    Edited 2018

    Concat is now available as database function:

    >>> 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()
    ...     )
    ... )
    

提交回复
热议问题