sqlalchemy-mixins icon indicating copy to clipboard operation
sqlalchemy-mixins copied to clipboard

How to cover the original model by TimestampsMixin?

Open vba34520 opened this issue 2 years ago • 3 comments

I have a table in MySQL like this

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

Auto generate

pip install pymysql
pip install sqlacodegen

sqlacodegen mysql+pymysql://root:[email protected]:3306/test

Result

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    created_at = Column(DateTime)
    updated_at = Column(DateTime)
    deleted_at = Column(DateTime)

And I combine it with sqlalchemy_mixins

main.py

from flask import Flask
from sqlalchemy_mixins import AllFeaturesMixin
from sqlalchemy_mixins.timestamp import TimestampsMixin
from sqlalchemy import Column, Integer, String, DateTime
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]:3306/test'
db = SQLAlchemy(app, session_options={'autocommit': True})


class Base(db.Model, AllFeaturesMixin, TimestampsMixin):
    __abstract__ = True


class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    created_at = Column(DateTime)
    updated_at = Column(DateTime)
    deleted_at = Column(DateTime)


Base.set_session(db.session)
db.create_all()

if __name__ == '__main__':
    user = User.create(name='Bob')
    print(user.to_dict())
    # {'id': 1, 'name': 'Bob', 'created_at': None, 'updated_at': None, 'deleted_at': None}

How to make created_at and updated_at are not None without deleting their statements?

vba34520 avatar Sep 08 '22 13:09 vba34520

Remove created_at and updated_at from the User model definition and it should work as intended.

michaelbukachi avatar Sep 08 '22 14:09 michaelbukachi

First, Removing them manually will increase workload after auto generate.

Second, It will affect the original order of fields.

vba34520 avatar Sep 10 '22 14:09 vba34520

How to achieve logical deleting by deleted_at? Thanks!

For example, a user record's deleted_at was set. I hope Product.find_or_fail(id) will raise sqlalchemy_mixins.ModelNotFoundError.

vba34520 avatar Oct 08 '22 09:10 vba34520