marshmallow
marshmallow copied to clipboard
only option not working properly for nested fields.
from marshmallow import Schema, fields
class Address:
def __init__(self, street, country):
self.street = street
self.country = country
class User:
def __init__(self, name, email, location):
self.name = name
self.email = email
self.location = location
class Blog:
def __init__(self, id, title, author):
self.title = title
self.id = id
self.author = author
class AddressSchema(Schema):
street = fields.String()
country = fields.String()
class UserSchema(Schema):
name = fields.String()
email = fields.Email()
location = fields.Nested(AddressSchema)
class BlogSchema(Schema):
id = fields.Int()
title = fields.String()
author = fields.Nested(UserSchema, only=['location'])
address = Address(street='4 cross', country='myCountry')
user = User(name="Anantha", email="[email protected]", location=address)
blog = Blog(id = 1, title="nested only test", author=user)
print(BlogSchema(only=['title','author.location.street']).dump(blog))
Actual Result: {'title': 'nested only test', 'author': {}}
Expected Result: {'title': 'nested only test', 'author': {'location': {'street': '4 cross'}}}
Note: if I change
author = fields.Nested(UserSchema, only=['location']) to
author = fields.Nested(UserSchema, only=['location.street']) it works.
But, This does not solve purpose as there may be many fields in location nested field and need different fields for different scenarios.
I'm seeing the only= field completely ignored in my code. It dumps every single field in the nested object. We're working around it for now by using the exclude= instead but this obviously needs maintenance every time we change the nested schema.