3
votes

AttributeError: sqlalchemy object has no attribute "Models" and some times ModuleNotFoundError: No module named 'models' error is occurring. I already installed all requirements like pip install sqlalchemy, flask-sqlalchemy, psycopy2-binary.

import os

from flask import Flask, render_template, request
from models import *

app = Flask(__name__)

app.config["SQLALchemy_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALchemy_TRACK_MODIFICATIONS"] = False
db.init_app(app)

def main():
    db.create_all()

if __name__ == "__main__":
    with app.app_context():
        main()

Traceback (most recent call last): File "create.py", line 5, in from models import * AttributeError: sqlalchemy object has no attribute "Models"

2
What does your models.py (or package) look like? - Doobeh
The error will be in your models module, can you include the contents of that? I’m guessing that somewhere you have a class inheriting from db.Models rather than db.Model although I can only guess until I see the code. - SuperShoot
from flask_sqlalchemy import SQLAlchemy db=SQLAlchemy() class Flight(db.Models): tablename = "flights" id = db.Column(db.Integer, primary_key=True) origin = db.Column(db.String, nullable=False) destination = db.Column(db.String, nullable=False) duration = db.Column(db.Integer, nullable=False) class Passenger(db.Models): tablename = "passengers" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) flight_id = db.Column(db.Integer, db.ForeignKey("flights.id", nullable=False)) - sheraz_arain
file name is models.py - sheraz_arain
Change all of the db.Models to db.Model. - SuperShoot

2 Answers

0
votes

Make shure in your models.py in your db object is

db = SQLAlchemy()

NOT db = SQLAlchemy , because SQLAlchemy is a class

0
votes

If it doesn't work try the following.

db.init_app(app)

For example


#main.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'  # Database URL
db = SQLAlchemy(app)
db.init_app(app)