Home > database >  Inserting data right after create table in SqlAlchemy
Inserting data right after create table in SqlAlchemy

Time:02-11

I'm creating my tables with SqlAlchemy and have a table called UserTypes

id | type

0 | Owner

1 | Customer

In my User table i take usertype id as foreign key. And whenever i want to create a user, i want to assign usertype default 0. But my usertype table is empty, so i want to fill this table right after its created with SqlAlchemy, and locked for further insertions. Question is can i insert

Here is my User and UserType modals.

class User(Model):       

    id = Column(db.Integer, primary_key=True)
    email = Column(db.String(64), unique=True, index=True)
    username = Column(db.String(15), unique=True, index=True)
    name = Column(db.String(64))
    password_hash = Column(db.String(128))
    usertype_id = Column(db.Integer, db.ForeignKey('user_types.id'), default=DEFAULT_USERTYPE)

and

class UserType(db.Model):

   __tablename__ = 'user_types'
   id = db.Column(db.Integer, primary_key=True)
   name = db.Column(db.String(64), index=True, unique=True)   
   users = db.relationship('User', backref='user_types', lazy='dynamic') 
   

CodePudding user response:

You could add those UserTypes in your app/__init__.py. You would have to check under which key the table gets saved, I'm not sure if it would be 'usertype' or 'user_types'.

if 'user_types' not in db.metadata.tables.keys():
    db.create_all()
    t1 = UserType()
    t1.id = 0
    t1.name = 'Owner'
    db.session.add(t1)
    t2 = UserType()
    t2.id = 1
    t2.name = 'Customer'
    db.session.add(t2)
    db.session.commit()
  • Related