Comments (10)
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.
@adregan Can this issue be closed?
from marshmallow.
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.
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.
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.
@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.
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.
@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.
@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.
@sloria Great! Thanks :)
from marshmallow.
Related Issues (20)
- Question - Is it possible to ignore fields on dump? HOT 4
- sdist is missing `tox.ini` HOT 4
- Validation does not occur on serialization documentation issue HOT 2
- Dot in key is not parsed correclty on loads() HOT 3
- The data_key argument for one or more fields collides with another field's name or data_key argument. HOT 2
- Serialize data objects in Schema HOT 1
- Raise error for valid e-mail
- Is this safer than Pickle? HOT 1
- Wrong value in __call__() function of validate.Validator HOT 1
- Validation of required nested field is not consistent with previous version
- Create raw list Schema HOT 1
- The function decorated by the "post_load" decorator will undergo changes in parameter types as the function name changes. HOT 1
- Deprecate __version__ and related attributes
- Address deprecation warnings in tests HOT 1
- URL validation fails if URL is missing user field HOT 5
- fields.URL validation error should specify "not a valid FQDN" if trying to pass hostname without domain
- missing `f` for f-Strings HOT 2
- `fields.Url` does not accept `file` URLs
- when a new request, schema context not reset !!! HOT 2
- Questions about Copilot + Open Source Software Hierarchy HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from marshmallow.