Skip to content

"values_list" equivalent with flat=True functionality #11

@SEJeff

Description

@SEJeff

I watched a consumer of an API using this iterate over and over on a list of dicts for 1 field. In the Django ORM, this is where something like foo_queryset.values_list('name', flat=True) would be a no brainer to make it easier to use the results.

Based on the conversation I've already had with @wimglenn this seems to be the blessed approach:

  1. fields_list instead of fields will return an array of arrays (list of lists) since this is JSON we're talking about
  2. fields_list queries can have an optional flat query argument which will flatten the array of arrays into a single array containing the results akin to flat=True will when calling a queryset with values_list()
  3. Due to keys being inherently unordered, fields_list!=foo,bar,baz will not be supported as there is no way to predetermine the field ordering.
  4. Any request using multiple fields along with flat should return a HTTP 400 Bad Request e.g: fields_list=foo,bar&flat is invalid.

So given data from this request:

GET /api/animals/?fields=name,type

{
    count: 2,
    next: null,
    previous: null,
    results: [
        {
            name: "wombat",
            type: "marsupial"
        },
        {
            name: "wallaby",
            type: "marsupial"
        }
    ]
}

A query such as:

GET /api/animals/?fields_list=name,type

Would return data such as:

{
    count: 2,
    next: null,
    previous: null,
    results: [
        ["wombat", "marsupial"],
        ["wallaby", "marsupial"]
    ]
}

GET /api/animals/?fields_list=name&flat or GET /api/animals/?fields_list=name&flat=true

Would return data such as:

{
    count: 2,
    next: null,
    previous: null,
    results: [
        [
            "wombat",
            "wallaby"
        ],
    ]
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions