ebarbara
ebarbara

Reputation: 165

Django Rest Framework: Convert serialized data to list of values

I'm using a DRF ModelSerializer to serve a one-field queryset, but the response returns as a list of dicts

[{"state": "AL"}, {"state": "AR"}, {"state": "AZ"}]

Is there any way to return a pure string list, like ["AL", "AR", "AZ"] ? I've explored other questions, but haven't found anything useful.

Upvotes: 0

Views: 1545

Answers (1)

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10709

If you just need the state, you can extract the data out of that list of dicts:

response = [{"state": "AL"}, {"state": "AR"}, {"state": "AZ"}]
states = [data.get("state") for data in response]
print(states)

Output

['AL', 'AR', 'AZ']

Upvotes: 1

Related Questions