Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

403
Views
Adding records into table while running the db init

I am using flask,sqlalchemy,sqlite and python for my application. When I run the db init for creating the database I want some default set of values hase to be added into the database. I have tried these two things to add the records into the table. One method is using 'event'.

from sqlalchemy.event import listen
from sqlalchemy import event, DDL

@event.listens_for(studentStatus.__table__, 'after_create')
def insert_initial_values(*args, **kwargs):
    db.session.add(studentStatus(status_name='Waiting on admission'))
    db.session.add(studentStatus(status_name='Waiting on student'))
    db.session.add(studentStatus(status_name='Interaction Initiated'))
    db.session.commit()

When I run

python manage_db.py db init,
python manage_db.py db migrate,
python manage_db.py db upgrade

I didnt get any issues but the records are not getting created.

The another method I tried is ,in the models.py I have included

record_for_student_status = studentStatus(status_name="Waiting on student")
db.session.add(record_for_student_status)
db.session.commit()
print(record_for_student_status)

The Class Model code:

class StudentStatus(db.Model): 
   status_id = db.Column(db.Integer,primary_key=True) 
   status_name = db.Column(db.String) 
   def __repr__(self): 
      return f"studentStatus('{self.status_id}','{self.status_name}')" 

When I run python manage_db.py db init ,I am getting an error Student_status,there is no such table.

Can some one help me how to add the default values to the student_status table when I run db init?

I have tried with flask-seeder also. I have installed flask seeder nd added one new file called seeds.py and I ran the flask seed run

My seeds.py looks like this

class studentStatus(db.Model):
  def __init__(self, status_id=None, status_name=None):
    self.status_id = db.Column(db.Integer,primary_key=True)
    self.status_name = db.Column(db.String,status_name) 

  def __str__(self):
    return "ID=%d, Name=%s" % (self.status_id, self.status_name)



class DemoSeeder(Seeder):

  # run() will be called by Flask-Seeder
  def run(self):
    # Create a new Faker and tell it how to create User objects
    faker = Faker(
      cls=studentStatus,
      init={
        "status_id": 1,
        "name": "Waiting on Admission"

      }
    )

    # Create 5 users
    for user in faker.create(5):
      print("Adding user: %s" % user)
      self.db.session.add(user)

I ran db init,db migrate and db upgrade. I didnt get any issues. When I ran flask seed run I am getting this error

Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory

I googled it and i tried export FLASK_APP=seeds.py

Then I ran the flask seed run ,I am getting an error ``` error could not import seeds.py```
Please help me in this.
What I need finally is when I do db initialization for the first time some default value have to be added to the database.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

humm, seems like you put a underscore in Student_status, try to remove it. And other thing, try to write your class in CamelCase, is more "Pythonic" way to write a code, when you run it, the SQLalchemy will transform this class name to student_status table automatically

over 4 years ago · Santiago Trujillo Report

0

Before running the flask application you should instantiate the FLASK_APP and FLASK_ENV.

First Create a function for adding data. assume that the function name is run like yours,

def run(self):
    # Create a new Faker and tell it how to create User objects
    faker = Faker(
      cls=studentStatus,
      init={
        "status_id": 1,
        "name": "Waiting on Admission"

      }
    )

    # Create 5 users
    for user in faker.create(5):
      print("Adding user: %s" % user)
      self.db.session.add(user)

Now you can call this function in the app running file. Assume that my file has named as app.py.

from application import app
if __name__ == '__main__':
     run()
     app.run(debug=True)

Now set the FLASK_APP and FLASK_ENV like below.

export FLASK_APP=app.py
export FLASK_ENV=development

After that, you can run the below commands.

flask db init
flask db  migrate
flask db upgrade

this will create all the tables and the data what you want.

For more details, you can get from the below link. This link is for a Github repository. There I have done adding some data when app initiating. Just read the readme.MD then you can get some more insight about setting up the FLASK_APP.

Flask Data Adding when DB instantiating

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!