What exactly is the attribute in marshmallow.fields.Nested() function?

Viewed 1195

I am trying to nest a Schema inside another Schema like the following:

class RecipePaginationSchema(PaginationSchema):
    data = fields.Nested(RecipeSchema, attribute = "items", many = True)

The result should look something like this:

{
    "links": {
        "first": "http://localhost:5000/users/name/recipes?per_page=2&visibility=all&page=1",
        "last": "http://localhost:5000/users/name/recipes?per_page=2&visibility=all&page=2",
        "next": "http://localhost:5000/users/name/recipes?per_page=2&visibility=all&page=2"
    },
    "page": 1,
    "pages": 2,
    "per_page": 2,
    "total": 3,
    "data": [
        {
            "id": 11,
            ...
        }
}

However, when I tried to use another attribute instead of "items", I didn't get the "data" part in the JSON response. So, what exactly is this attribute thing referring to?

By the way, I'm following Packt's Python API Development Fundamentals book.

1 Answers

From the documentation:

attribute – The name of the attribute to get the value from when serializing. If None, assumes the attribute has the same name as the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use data_key instead.

In other words, you map your field 'data' in the RecipePaginationSchema to the attribute 'items' in the RecipeSchema.

I don't know your use case, but as explained in the documentation, you should use the attribute keyword as a last resort. Many use cases can be solved with the 'only' and 'exclude' keywords (see here).

Related