How to handle the __init__function by using dataclass, Sqlalchemy and marshmallow_sqlalchemy

496 views Asked by At

In the current stable version of SQLAlchemy there is no method to map the Model to a data class (which is supposed to be available in v1.4). So I want to apply the ORM my self by defining:

class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String)

    def __init__(self, name: str):
        self.name = name

class UserSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = User
        load_instance = True

user_schema = UserSchema()

My goal is to use the schema to load the json data from REST API. But it seems that the automatically incrementable primary key id is a problem. Since the attribute id is only defined in the database but not in the attribute list. So when I apply user_schema.load(#some_json), I got the error report TypeError: __init__() got an unexpected keyword argument 'id'

The tracking error is like this:

@ma.post_load
    def make_instance(self, data, **kwargs):
        """Deserialize data to an instance of the model if self.load_instance is True.
        Update an existing row if specified in `self.instance` or loaded by primary key(s) in the data;
        else create a new row.
    
        :param data: Data to deserialize.
        """
        if not self.opts.load_instance:
            return data
        instance = self.instance or self.get_instance(data)
        if instance is not None:
            for key, value in data.items():
                setattr(instance, key, value)
            return instance
        kwargs, association_attrs = self._split_model_kwargs_association(data)
>       instance = self.opts.model(**kwargs)
E       TypeError: __init__() got an unexpected keyword argument 'id'

../../environments/xxx/lib/python3.7/site-packages/marshmallow_sqlalchemy/schema/load_instance_mixin.py:74: TypeError

My question is, how should I define the model class, with the aim that I can use it as a normal data class, and also an ORM model in SQLAlchemy at the same time?

1

There are 1 answers

0
robin On BEST ANSWER

It seems that I can just adapt the schema like this and the __init__() problem can be solved:

class UserSchema(SQLAlchemyAutoSchema):
class Meta:
    model = User
    load_instance = True
    exclude = ["id"]