absent1706/sqlalchemy-mixins

[question] Could you please clarify how to use it with Flask-Sqlalchemy?

bakanov opened this issue · 2 comments

In Flask-Sqlalchemy I inherit my models from db.Model .
It's hard for me to understand how to write my models if I use sqlalchemy-mixins

Hello, bakanov

You can to create a common class (eg. BaseModel) that inherits from db.Model and some sqlalchemy-mixins class.

So, you will write your models as if they were normal Flask-SQLAlchemy models but inheriting from BaseModel.

A minimal example would be:

import sqlalchemy as sa
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_mixins import ActiveRecordMixin

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)


class BaseModel(db.Model, ActiveRecordMixin):
    __abstract__ = True
    pass


class User(BaseModel):
    __tablename__ = 'user'
    __repr_attrs__ = ['name']
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)
    posts = sa.orm.relationship('Post', backref='user')
    posts_viewonly = sa.orm.relationship('Post', viewonly=True)

In tests you can find other examples.

Hi!
I added working code snippet to Readme , see https://github.com/absent1706/sqlalchemy-mixins#usage-with-flask-sqlalchemy

Thanks!