Search code examples
pythonenumsmarshmallow

How to enable marshmallow-enum EnumField to correct serialize EnumField?


When I try to serialize Python objects in JSON format using marshmallow and marshmallow-enum package AttributeError has been triggered - 'str' object has no attribute 'name'

I have the following classes linked with foreign keys:

class BusinessUnitsManagement(db.Model, DatabaseObject):
    __tablename__ = 'bu_mngmt'
    id = db.Column(db.Integer(), primary_key=True)
    bu_id = db.Column(db.Integer(), db.ForeignKey('business_units.id'), nullable=False)
    head = db.Column(db.Integer(), db.ForeignKey('user_properties.id'), nullable=True)

    bu_properties = db.relationship('BusinessUnits', foreign_keys=[bu_id], backref='bu_mngmt')
    head_properties = db.relationship('UserProperty', foreign_keys=[head])

class UserProperty(db.Model, DatabaseObject):
    __tablename__ = 'user_properties'
    id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
    seniority = db.Column(db.Enum(Seniority), nullable=True)

class BusinessUnits(db.Model):
    __tablename__ = 'business_units'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(5), nullable=False)
    description = db.Column(db.String(100), nullable=True)

And also, I create Schema classes for these above classes:

from marshmallow import Schema, fields
from marshmallow_enum import EnumField

class BusinessUnitsManagementSchema(Schema):
    id = fields.Int()
    bu_properties = fields.Nested(BusinessUnitsSchema)
    head_properties = fields.Nested(UserPropertySchema)

class UserPropertySchema(Schema):
    id = fields.Int()
    full_name = fields.Str()
    seniority = EnumField(Seniority)

class BusinessUnitsSchema(Schema):
    id = fields.Int()
    name = fields.Str()
    description = fields.Str()

Seniority is defined as:

Seniority = Enum(
    value='Seniority',
    names=[
        ('Intern', 'Intern'),
        ('Junior_Engineer', 'Junior_Engineer'),
        ('Junior Engineer', 'Junior Engineer'),

        ('Design Engineer', 'Design Engineer'),
        ('Design_Engineer', 'Design_Engineer'),

        ('Senior Engineer', 'Senior Engineer'),
        ('Senior_Engineer', 'Senior_Engineer')
    ]
)

When I try to get JSON format of Python objects:

from marshmallow import Schema, fields
from marshmallow_enum import EnumField

objects = BusinessUnitsManagement.query.join(BusinessUnits).all()
result = []
for object in objects:
    marshmallow_item = BusinessUnitsManagementSchema.dumps(object)
    result.append(marshmallow_item.data)
return result

I get this error on Ubuntu, but on Windows everything is ok:

marshmallow-enum version on both Win and Ubuntu --- 1.5.1
Python version on Win 10 ---------- 3.6.6
Python version on Ubuntu 16.04.3 -- 3.5.2 

   marshmallow_item = schema.dumps(item)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/schema.py", line 557, in dumps
    deserialized, errors = self.dump(obj, many=many, update_fields=update_fields)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/schema.py", line 509, in dump
    **kwargs
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 138, in serialize
    index=(index if index_errors else None)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 62, in call_and_store
    value = getter_func(data)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 132, in <lambda>
    getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/fields.py", line 252, in serialize
    return self._serialize(value, attr, obj)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/fields.py", line 450, in _serialize
    update_fields=not self.__updated_fields)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/schema.py", line 509, in dump
    **kwargs
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 138, in serialize
    index=(index if index_errors else None)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 62, in call_and_store
    value = getter_func(data)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/marshalling.py", line 132, in <lambda>
    getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow/fields.py", line 252, in serialize
    return self._serialize(value, attr, obj)
  File ".../flaskvenv/lib/python3.5/site-packages/marshmallow_enum/__init__.py", line 80, in _serialize
    return value.name
AttributeError: 'str' object has no attribute 'name'

Solution

  • The problem is related to the database, more specifically the problem was with values for column 'seniority'. Some rows have 'seniority' set as blank (not NULL - just empty string), so that is the reason why serialization is not properly done. I don't know how that happened because the 'seniority' column is set as ENUM type.