简体   繁体   中英

How do i alias a composite value of 2 fields inside the values_list method of object_manager?

I am trying to create a really simple form that allows the user to select an active user from a selection list and submitting that choice to the backend. Here is my code:

class PeerReviewColleagueSelectionForm(forms.Form):
    ACTIVE_COLLEAGUES = CustomUser.objects.filter(is_active=True)\
        .values_list('id', full_name=F(('first_name') + ' ' + F('last_name')))\
        .order_by('full_name').annotate(Count='id')
    colleague = forms.ChoiceField(label='selecteer collega', tuple=ACTIVE_COLLEAGUES)

I am trying to get a list of tuples that can be used by the ChoiceField widget to display all the available active colleagues to choose from.

I'm trying to create an alias called full_name from the first_name and last_name fields of CustomUser. Then I want to order the results by that alias and i use annotate(count) to group by id (since i know each id is unique and i want tuples consisting of (id, full_name,)

However when i try this it throws: TypeError: values_list() got an unexpected keyword argument 'full_name'

How can i make a tuple based on the id and an alias called full_name?

Unfortunatelly values_list() doesn't accept expression keywords arguments. So you should annotate new field first:

CustomUser.objects.filter(is_active=True)
    .annotate(full_name=Concat('first_name', Value(' '), 'last_name') 
    .values_list('id', "full_name")
    .order_by('full_name')

Note that you can use Concat database function to perform string concationation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM