webmourek
webmourek

Reputation: 59

How to filter object from model User into list

I am trying to make a list from users I filter, which is here:

User.objects.filter(groups__name='Staff')

output which I want it something like

list_of_usernames = [adam, joe, natalie]

In list has to be username of the user. Can some please help me to write that query? I tried something to_list but it did not work out for me.

Upvotes: 1

Views: 407

Answers (2)

Eduardo Balbinot
Eduardo Balbinot

Reputation: 139

If you won't need any other attribute from the user for later use, just do:

list_of_usernames = [u.username for u in User.objects.filter(groups__name='Staff')]

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

You can make use of .values_list(..) [Django-doc] here:

list_of_usernames = list(
    User.objects.filter(groups__name='Staff').values_list('username', flat=True)
)

But actually it is usually better to fetch model objects, and fetch the attribute, such that the logic in the model is not "bypassed":

from operator import attrgetter

list_of_usernames = list(map(
    attrgetter('username'),
    User.objects.filter(groups__name='Staff')
))

Upvotes: 2

Related Questions