question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

fields.Nested should optionally pass the parent object to the Nested Schema

See original GitHub issue

As described in #900, there is no obvious way to create a nested serialization from a flat object. To fix this, fields.Nested should accept an optional from_parent argument. When true, the nested Schema is passed the parent object rather than the attribute at the field name. from_parent will default to False, which will maintain current behavior.

Any feedback on this idea? I plan on implementing it soon.

Thanks, James

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:6
  • Comments:12 (7 by maintainers)

github_iconTop GitHub Comments

2reactions
multimericcommented, Aug 22, 2019

I also solved this using a (simpler) variant of @m-a-choquette’s method:

class SelfNested(fields.Nested):
    def get_value(self, obj, attr, accessor=None, default=missing):
        return obj

This let me use this schema:

class SampleFilterSchema(with_metaclass(SchemaMeta, BaseModelSchema)):
    class Meta:
        model = SampleFilter

    id = fields.Integer(attribute='sample_filter_id')
    type = fields.Constant('filter')
    attributes = SelfNested(Schema.from_dict(dict(
        tag=fields.String(attribute='sample_filter_tag'),
        name=fields.String(attribute='sample_filter_name'),
        public=fields.Boolean(attribute='is_public'),
        data=JsonString(attribute='sample_filter_data'),
        user=ResourceHyperlink(endpoint='rest_api.user', url_args=[
            'user_id',
        ])
    )))

(ignore my custom fields, they’re not important for this example)

Which transforms:

{  
   "user_id":1,
   "is_public":false,
   "sample_filter_name":"TestFilter",
   "sample_filter_data":"",
   "sample_filter_tag":"Global",
   "sample_filter_id":1
}

into

{
   "id":1,
   "attributes":{
      "user":"/rest_api/v1/users/1",
      "tag":"Global",
      "public":false,
      "name":"TestFilter",
      "data": ""
   }
}

aka, a valid response (or segment thereof) under the JSON API standard!

2reactions
m-a-choquettecommented, Dec 19, 2018

Hi, It feels a little weird to set a property on the object while serializing it.

To work around this, we did something like this:

def identity_accessor(attr, obj, default):
    return obj or default


class Section(fields.Nested):
    def get_value(self, attr, obj, accessor=None, default=missing):
        return super(Section, self).get_value(attr, obj,
                                              accessor=identity_accessor,
                                              default=default)

Each Section field receives the full object.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Nesting Schemas — marshmallow 3.19.0 documentation
Schemas can be nested to represent relationships between objects (e.g. ... Use a Nested field to represent the relationship, passing in a nested...
Read more >
Marshmallow serialize nested with parent field - Stack Overflow
In marshmallow it's possible to pass values from a parent scheme to its children before serialization by using the pre_dump decorator on the ......
Read more >
Nested field type | Elasticsearch Guide [8.5] | Elastic
The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way...
Read more >
marshmallow - Bountysource
To fix this, fields.Nested should accept an optional from_parent argument. When true, the nested Schema is passed the parent object rather than the ......
Read more >
Nested - OpenSearch documentation
By default, each of the nested objects is dynamically mapped as object field type. Any object field can take an array of objects....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found