Home > Software design >  How to change the class attributes of the instance of the SQLAlchemyAutoSchema
How to change the class attributes of the instance of the SQLAlchemyAutoSchema

Time:11-04

I have a flask_sqlalchemy model that I want to serialize its instance and a list of its instances using 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

To do so, I create two instances of the above class as below:

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)}

So what is serialized_test? It is what I want and it looks like this:

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

And what is serialized_tests? It looks like this:

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

But I do not need comments. I just need:

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

How can I have this without having to redefine another TestSchema such as TestListSchema?

If I could do something like this it would be really helpful:

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

What I am actually trying to do is to remove class attributes from the instance.

Any solution of how to do that?

Or if I could conditionally add attributes to the class

# 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

any solution?

CodePudding user response:

Simply do the following:

test_list_schema = TestSchema(many=True, exclude=("test_comments",))  # Don't forget the comma
  • Related