Francois
Francois

Reputation: 166

Use order output parameter and specify serialization key with marshmallow-sqlalchemy

I'm using marshmallow 3.4.0 and marshmallow-sqlalchemy 0.22.2

I have this SQLAlchemy model and Marshmallow schema

class Zone(Base):
    zone_id = Column(Integer, primary_key=True)
    name = Column(String(65))
    location_id = Column(Integer, ForeignKey('locations.location_id'))
    location = relationship("Location", lazy="joined")

class ZoneSchema(SQLAlchemySchema):
    class Meta:
        model = Zone
        fields = ("zone_id", "name", "location")
        ordered = True
        load_instance = True

    zone_id = auto_field(data_key="id")
    location = fields.Nested(LocationSchema)

If I remove zone_id = auto_field(data_key="id") the fields are ordered as requested.

If I remove

fields = ("zone_id", "name", "location")
ordered = True

The key is set to id as requested.

If I run the code above, I get this error


  File "[...]/models_schema.py", line 30, in <module>
    class ZoneSchema(SQLAlchemySchema):
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 107, in __new__
    cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 57, in _get_fields
    fields.sort(key=lambda pair: pair[1]._creation_index)
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 57, in <lambda>
    fields.sort(key=lambda pair: pair[1]._creation_index)
AttributeError: 'SQLAlchemyAutoField' object has no attribute '_creation_index'

Could someone explain to me how I can set access the zone_id field and add the "data_key" property ?

Upvotes: 0

Views: 926

Answers (1)

Francois
Francois

Reputation: 166

As a last resort, I read the documentation and I managed to find an answer by myself.

class ZoneSchema(SQLAlchemySchema):
    class Meta:
        model = Zone
        fields = ("zone_id", "name", "location")
        ordered = True
        load_instance = True

    location = fields.Nested(LocationSchema)

    @pre_dump
    def set_data_key_for_zone_id(self, data, many, **kwargs):
        self.fields.get("zone_id").data_key = "id"
        return data

As you can see, I kept the ordered = True part and use the pre-dump decorator to access the zone_id field and set the data_key attribute.

If there is a better way to do this, please let me/us know !

Upvotes: 1

Related Questions