stefanobaldo
stefanobaldo

Reputation: 2063

Create a base model class

I'm using flask-sqlalchemy. I currently declare my models using:

class MyModel(db.Model):
    __tablename__ = 'my_table'
    id = db.Column(db.Integer, primary_key=True)
    ...

I want to create a base model class so I will be able to declare my models like this:

class MyBase(db.Model):
    pass

class MyModel(MyBase):
    __tablename__ = 'my_table'
    id = db.Column(db.Integer, primary_key=True)
    ...

Is it possible? I'm getting the following error:

InvalidRequestError: Class <class 'api.models.base.base_model.BaseModel'> does not have a __table__ or __tablename__ specified and does not inherit from an existing table-mapped class.

I would want to be able to put the tablename and all the column attributes inside my model and not inside my base class.

Upvotes: 0

Views: 2646

Answers (1)

davidism
davidism

Reputation: 127190

Since your custom base model is not a real model, you need to tell SQLAlchemy that it is abstract by setting __abstract__ = True on the class.

class MyBase(db.Model):
    __abstract__ = True

Unless you are adding common functionality to this custom base, there's no point in doing this. The empty custom base is basically equivalent to just inheriting from db.Model directly.

Upvotes: 4

Related Questions