Marshmallow: Cannot have multiple fields use the same attribute

Created on 3 Nov 2018  Â·  3Comments  Â·  Source: marshmallow-code/marshmallow

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 https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/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

backwards incompat feedback welcome

Most helpful comment

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.

All 3 comments

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.

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

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zohuchneg picture zohuchneg  Â·  3Comments

imhoffd picture imhoffd  Â·  3Comments

k0nsta picture k0nsta  Â·  4Comments

lupodellasleppa picture lupodellasleppa  Â·  3Comments

j4k0bk picture j4k0bk  Â·  3Comments