Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SQLAlchemy how do I populate rows after creating the db using db.create_all()

I have a create_all call in my SQLAlchemy app.py

@app.before_first_request
def create_tables():
    db.create_all()

And define a basic user in a user.py model file:

class UserModel(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(80))
    password = db.Column(db.String(80))

    def __init__(self, username, password):
        self.username = username
        self.password = password

I want to pre-populate some default data, in this example some base users:

    admin = self('admin', 'test')
    guest = self('guest', 'test')

Can I input them in the app.py somehow? Or in another create_data.py type file?

like image 675
Jeuke Avatar asked Dec 18 '16 08:12

Jeuke


1 Answers

You could create an example_data.py file like this:

from user import UserModel

def db_load_example_data(app, db):
    admin = UserModel('admin', 'test')
    guest = UserModel('guest', 'test')
    with app.app_context():
        db.session.add(admin)
        db.session.add(guest)
        db.commit()

and then in your startup script you can call this

from example_data import db_load_example_data

db_load_example_data(app, db)
like image 110
Stijn Diependaele Avatar answered Oct 24 '22 01:10

Stijn Diependaele