0

I have a pretty regular schema class like:

class TestSchema(db_schema.SQLAlchemyAutoSchema):
    xxx = fields.Str()
    name = fields.Str(validate=validate.Length(min=1), required=True, error_messages={"required": "The name is required."})
    class Meta:
        fields = ('id', 'name', 'description')
        model = TestModel

And I would like to analyze the class itself to be able to form some metainformation for the frontend. But I can't access xxx nor name like:

schema_instance = TestSchema()
schema_instance.xxx ???AttributeError: 'TestSchema' object has no attribute 'xxx'
mimic
  • 4,897
  • 7
  • 54
  • 93

1 Answers1

2

As @maruthi-adithya comments, you need to define another class to dump the result of TestSchema; you'll need to make use of postload which handles post-deserialization in which you can return the data as you need, check the documentation for it here. Below an example:

class Test:
    def __init__(self, xxx, name, id):
        self.xxx = xxx
        self.name = name
        self.id = id
    def __repr__(self):
        return (
            f'<Test(xxx={self.id}, name={self.name})'
        )


class TestSchema(db_schema.SQLAlchemyAutoSchema):
    xxx = fields.Str()
    name = fields.Str(validate=validate.Length(min=1), required=True, error_messages={"required": "The name is required."})
    id = fields.Integer()
    class Meta:
        fields = ('id', 'name', 'description')
        model = TestModel

    @postload
    def return_as_object(self, data, **kwargs):
        return Test(**data)
Loscil94
  • 73
  • 5