miLibris / flask-rest-jsonapi

Flask extension to build REST APIs around JSONAPI 1.0 specification.
http://flask-rest-jsonapi.readthedocs.io
MIT License
598 stars 153 forks source link

Querying of sparse fieldsets does not work #209

Open joe-at-siemens opened 3 years ago

joe-at-siemens commented 3 years ago

The 'only' attribute is set only after the schema has been instantiated in the compute_schema method, and so the set of attributes that are then returned in the dump method has already been determined.

joe-at-siemens commented 3 years ago

A workaround is to make a call to _init_fields() after schema.only is set:

if schema.opts.type_ in qs.fields:
        tmp_only = set(schema.declared_fields.keys()) & set(qs.fields[schema.opts.type_])
        if schema.only:
            tmp_only &= set(schema.only)
        schema.only = tuple(tmp_only)

        # make sure again that id field is in only parameter unless marshamllow will raise an Exception
        if schema.only is not None and 'id' not in schema.only:
            schema.only += ('id',)
        schema._init_fields()