Cheknov
Cheknov

Reputation: 2082

How to update a queryset to include User's full name

Currently in my project I use the following code to obtain a list of Users:

all_manager = User.objects.filter(id__in=manager_list).values(
    "id", "first_name", "last_name"
)

For the User model there is no field called 'full_name' or something similar.

I read the official documentation and there is a method get_full_name()

The question is: How can I modify the queryset to include a 'full_name' key with its value?

Dummy Queryset:

<QuerySet [{'id': 1, 'first_name': 'Steve', 'last_name': 'Jobs'}, {'id': 3, 'first_name': 'Tim', 'last_name': 'Cook'}]>

Desired Queryset:

<QuerySet [{'id': 1, 'first_name': 'Steve', 'last_name': 'Jobs', 'full_name': 'Steve Jobs'}, {'id': 3, 'first_name': 'Tim', 'last_name': 'Cook', 'full_name': 'Tim Cook'}]>

Upvotes: 0

Views: 147

Answers (1)

acw
acw

Reputation: 948

You can use annotate. Just make sure you read up on the order (i.e. use annotate then values)

from django.db.models import CharField, Value
from django.db.models.functions import Concat

User.objects.annotate(
    full_name=Concat("first_name", Value(" "), "last_name", output_field=CharField())
).filter(id__in=manager_list).values("id", "first_name", "last_name", "full_name")

Ref: https://docs.djangoproject.com/en/dev/ref/models/database-functions/#concat

https://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-values-clauses

Upvotes: 4

Related Questions