0

first time poster, learning python at school.

I am building a flask app and trying to set up a database using SQLalchemy. When I run the app the database is created but has no structure(tables).

my app.py looks like this:

from flask import Flask, render_template, 
from flask_sqlalchemy import SQLAlchemy
from model import *

app = Flask(__name__)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
db = SQLAlchemy(app)
db.init_app(app)
db.create_all()

my model.py looks like this:

from datetime  import datetime
import db

class Post(db.Model):
    id=db.column(db.interger(), primary_key=True)
    title=db.column(db.string(225),nullable=False)
    slug=db.column(db.string(225), nullable=False)
    content=db.column(db.text(), nullable=False)
    created_on = db.column(db.DateTime(), default=datetime.utcnow)
    updated_on=db.column(db.DateTime(), default=datetime.utcnow, onupdate=datetime )

I believe the database is not connected to the model.py file.

  • The code in `app.py`, including `db.create_all()` is executed before the code in `model.py`, so the tables are not created. You need to restructure your code so that `create_all()` executes after the model code. See the linked duplicates for more - the second one in particular applies to your case. – snakecharmerb Apr 06 '22 at 06:10

0 Answers0