Search code examples
djangodjango-rest-frameworkdjango-serializer

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.


Solution

  • 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']