Coder Social home page Coder Social logo

Comments (10)

sloria avatar sloria commented on August 19, 2024

The Nested field allows you to pass a default argument to the constructor. You can set the default to an empty collection, like so:

class AuthorSchema(Serializer):
    name = fields.String()
    books = fields.Nested(BookSchema, many=True, allow_null=True, default=tuple())

a = Author(name='Monty', books=None)
a_ser = AuthorSchema(a)
a_ser.data
# OrderedDict([('name', 'Monty'), ('books', ())])

Does that answer your question?

from marshmallow.

sloria avatar sloria commented on August 19, 2024

@adregan Can this issue be closed?

from marshmallow.

adregan avatar adregan commented on August 19, 2024

I found a work around, but the method above didn't seem to work:

On GET, I'll pass the data to be serialized, what I was able to so was present null values as arrays by checking for instances of fields.Nested and if the data returned from the DB was None, pass an array instead.

This works, but what I was looking for was on POST serializing an empty array (in the same way as serializing "Untitled" as a default string for a title field, let's say).

The desired output for the API was something like this

{
"entries": [
{
"title": "A title",
"body": "Blah blah blah",
"author": [{
  "id": "12345678",
  "name": "Sarah Something"
}],
"category": "Cool Category"
}
]}

where author is a nested field. However, if the author field was empty, I would want the following on POST or GET:

"author": []

but what I would get was:

"author": null

I think it's fine to close if this isn't an issue for others, but the fact that fields.Nested takes a default argument is something that isn't apparent from the documentation.

Thanks for your time.

from marshmallow.

sloria avatar sloria commented on August 19, 2024

I'm curious why setting many=True and default=tuple() did not work for you. Is an Entry's author field a many-to-one relationship? Can you please clarify how you implemented your solution?

from marshmallow.

miracle2k avatar miracle2k commented on August 19, 2024

It doesn't work for me either:

class DocumentSchema(Schema): pass

class BatchSchemaLoad(Schema):
    documents = fields.Nested(DocumentSchema, many=True, default=[])

Then::

In [6]: BatchSchemaLoad().load({})
Out[6]: UnmarshalResult(data={}, errors={})

In [7]: BatchSchemaLoad().load({'documents': []})
Out[7]: UnmarshalResult(data={'documents': []}, errors={})

from marshmallow.

sloria avatar sloria commented on August 19, 2024

@miracle2k The default parameter is only applied during serialization, not deserialization. See #45 for the discussion and rationale behind this.

Use Schema.preprocessor or make_object if you need to define defaults for deserialization.

from marshmallow.

adregan avatar adregan commented on August 19, 2024

Sorry all. Haven't had time to explore this, and I took my serialization in another direction. I don't store nested objects anymore but lists that reference the id and build the nested objects on GET.

It's been more helpful maintaining the current state of the data that way.

from marshmallow.

jimmyshen avatar jimmyshen commented on August 19, 2024

@sloria I'm using marshmallow to validate and unmarshal the JSON response from an API that can return null instead of a nested object. I'm representing these in the schema, like so:

class ApiResponse(Schema):
    entity = Nested(EntitySchema)

I believe this was the case discussed in issue #45.

Adding a preprocessor to shove in a default for the fields over and over did not seem like a maintainable solution for me, so I decided to just subclass fields.Nested, as below:

class NullableNested(Nested):
    def _deserialize(self, value):
        if value is None:
            return dict()
        return value

This seems to work, but I wanted to check if there are problems with this workaround.

Thanks

from marshmallow.

sloria avatar sloria commented on August 19, 2024

@jimmyshen Once #76 is implemented, you will be able to pass allow_none to a field. In the meantime, I think your solution is fine.

from marshmallow.

jimmyshen avatar jimmyshen commented on August 19, 2024

@sloria Great! Thanks :)

from marshmallow.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.