Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot have multiple fields use the same attribute #1038

Closed
sloria opened this issue Nov 3, 2018 · 3 comments
Closed

Cannot have multiple fields use the same attribute #1038

sloria opened this issue Nov 3, 2018 · 3 comments

Comments

@sloria
Copy link
Member

sloria commented Nov 3, 2018

#992 prevents two fields from using the same attribute. The intent was prevent user error.

However, there might be a legitimate use case where a user might want to serialize an attribute in two different ways. This was brought to my attention in marshmallow-code/marshmallow-sqlalchemy#121 .

To illustrate: say I have SchoolSchema which serializes both student_ids and nested representations of students.

from marshmallow import Schema, fields

class StudentSchema(Schema):
    id = fields.Int()

class SchoolSchema(Schema):
    student_ids = fields.Pluck(
        StudentSchema,
        'id',
        many=True,
        attribute='students',
    )
    students = fields.List(fields.Nested(StudentSchema))

schema = SchoolSchema()
# ValueError: The attribute argument for one or more fields collides with another field's name or attribute argument. Check the following field names and attribute arguments: ['students']

Is this a use case we want to support?

cc @lafrech

@lafrech
Copy link
Member

lafrech commented Nov 3, 2018

It works if dump_only is specified.

class SchoolSchema(Schema):
    student_ids = fields.Pluck(
        StudentSchema,
        'id',
        many=True,
        attribute='students',
        dump_only=True
    )
    students = fields.List(fields.Nested(StudentSchema))

At the time, we thought this was an acceptable compromise. If not, we may revert #992.

@sloria
Copy link
Member Author

sloria commented Nov 3, 2018

Yeah, and I still think it's an acceptable compromise. I just hadn't seen anyone try to do the above until I saw marshmallow-code/marshmallow-sqlalchemy#121 , which made me think it could be a legit use case.

@sloria
Copy link
Member Author

sloria commented Jan 10, 2019

Closing for now. Seems that the use case mentioned in marshmallow-code/marshmallow-sqlalchemy#121 was not broken. We can always reopen if this pops up again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants