使用订单输出参数并使用棉花糖-sqlalchemy指定序列化密钥

问题描述 投票:0回答:1

我正在使用棉花糖3.4.0和棉花糖-sqlalchemy 0.22.2

我有这个SQLAlchemy模型和棉花糖模式

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)

如果我删除zone_id = auto_field(data_key="id")字段按要求排序。

如果我删除

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

根据要求将密钥设置为id

如果运行上面的代码,则会出现此错误


  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'

有人可以向我解释如何设置访问zone_id字段并添加“ data_key”属性吗?

marshmallow-sqlalchemy
1个回答
0
投票

作为最后的选择,我阅读了文档,并设法自己找到了答案。

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

如您所见,我保留了ordered = True部分,并使用预转储修饰符来访问zone_id字段并设置data_key属性。

如果有更好的方法,请告诉我/我们!

© www.soinside.com 2019 - 2024. All rights reserved.