0

我有一个 flask_sqlalchemy 模型,我想使用 SQLAlchemyAutoSchema 序列化它的实例和它的实例列表:

class TestModel(Model):
    id = Column(Integer, primary_key=True)
    test_comments = relationship("TestCommentModel", backref=backref("test", lazy="joined"), 
        lazy="dynamic", foreign_keys="TestCommentModel.test_id")


    def find_by_id( ...  # 
    
    def find_all(...  # 


class TestSchema(ma.SQLAlchemyAutoSchema):

    test_comments = ma.Nested(TestCommentSchema, many=True)

    class Meta:
        model = TestModel
        dump_only = ("id",)
        load_instance = True
        include_fk = False

为此,我创建了上述类的两个实例,如下所示:

test_schema = TestSchema()
test_list_schema = TestSchema(many=True)

test = TestModel.find_by_id(test_id)
serialized_test = test_schema.dump(test)

tests = TestModel.find_all()
serialized_tests = {"tests": test_list_schema.dump(tests)}

那么什么是serialized_test?这是我想要的,它看起来像这样:

{"id":1, "comments": ["id": 1, "id":2]}

什么是serialized_tests?它看起来像这样:

{"tests": [
    {"id":1, "comments": ["id": 1, "id":2]},
    {"id":2, "comments": ["id": 3, "id":4]},
    ]
}

但我不需要评论。我只需要:

{"tests": [
    {"id":1},
    {"id":2},
    ]
}

我怎样才能拥有这个而不必重新定义另一个 TestSchema,例如 TestListSchema?

如果我能做这样的事情,那将非常有帮助:

test_schema = TestSchema()
test_list_schema = TestSchema(many=True)}
test_list_schema = test_list_schema.pop(test_comment)  # Pseudo Code

我实际上想要做的是从实例中删除类属性。

如何做到这一点的任何解决方案?

或者如果我可以有条件地向类添加属性

# Pseudo code
class TestSchema(ma.SQLAlchemyAutoSchema):

    if not many:
        test_comments = ma.Nested(TestCommentSchema, many=True)

    class Meta:
        model = TestModel
        dump_only = ("id",)
        load_instance = True
        include_fk = False

任何解决方案?

4

1 回答 1

1

只需执行以下操作:

test_list_schema = TestSchema(many=True, exclude=("test_comments",))  # Don't forget the comma
于 2021-11-03T04:28:41.527 回答