OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

'NoForeignKeysError' error when I try to load the app after script has been run

  • Thread starter Thread starter Dan
  • Start date Start date
D

Dan

Guest
I am pretty new to this side of Python so anything you see here will probably be wrong. Also, this is just a play around so if I do get the chance to publish this then I will be making it very secure don't worry!

Ok,

I am creating a page where users can upload items and the items uploaded are displayed on the index.html. I have created 2 models (trailers.db and users.db)

Code:
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import os
from datetime import datetime, timedelta
from dotenv import load_dotenv

app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'mysecret')
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///main.db"
app.config['SQLALCHEMY_BINDS'] = {
    'users': 'sqlite:///users.db',
    'trailers': 'sqlite:///trailers.db'
}
app.config['UPLOAD_FOLDER'] = 'static/uploads'
db = SQLAlchemy(app)

class User(db.Model):
    __bind_key__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
    
    # Relationship with Trailer model
    trailers = db.relationship('Trailer', backref='user', lazy=True)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}')"


class Trailer(db.Model):
    __bind_key__ = 'trailers'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text, nullable=False)
    price = db.Column(db.Float, nullable=False)
    make = db.Column(db.String(100), nullable=False)
    model = db.Column(db.String(100), nullable=False)
    year = db.Column(db.Integer, nullable=False)
    features = db.Column(db.Text, nullable=False)
    image = db.Column(db.String(100), nullable=False)
    is_sold = db.Column(db.Boolean, default=False)
    featured = db.Column(db.Boolean, default=False)
    upload_date = db.Column(db.DateTime, default=datetime.utcnow)
    sold_date = db.Column(db.DateTime, default=None)
    
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)

This is how it is being created

Code:
def create_db():
    with app.app_context():
        db.create_all()

if __name__ == '__main__':
    create_db()
    app.run(debug=True)

I get this error. Can someone help please?

Code:
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.trailers - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

I am also getting this error in my terminal when I run this python script.

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'trailers.user_id' could not find table 'users' with which to generate a foreign key to target column 'id'

Thanks
<p>I am pretty new to this side of Python so anything you see here will probably be wrong.
Also, this is just a play around so if I do get the chance to publish this then I will be making it very secure don't worry!</p>
<p>Ok,</p>
<p>I am creating a page where users can upload items and the items uploaded are displayed on the index.html. I have created 2 models (trailers.db and users.db)</p>
<pre><code>from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import os
from datetime import datetime, timedelta
from dotenv import load_dotenv

app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'mysecret')
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///main.db"
app.config['SQLALCHEMY_BINDS'] = {
'users': 'sqlite:///users.db',
'trailers': 'sqlite:///trailers.db'
}
app.config['UPLOAD_FOLDER'] = 'static/uploads'
db = SQLAlchemy(app)

class User(db.Model):
__bind_key__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)

# Relationship with Trailer model
trailers = db.relationship('Trailer', backref='user', lazy=True)

def __repr__(self):
return f"User('{self.username}', '{self.email}')"


class Trailer(db.Model):
__bind_key__ = 'trailers'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text, nullable=False)
price = db.Column(db.Float, nullable=False)
make = db.Column(db.String(100), nullable=False)
model = db.Column(db.String(100), nullable=False)
year = db.Column(db.Integer, nullable=False)
features = db.Column(db.Text, nullable=False)
image = db.Column(db.String(100), nullable=False)
is_sold = db.Column(db.Boolean, default=False)
featured = db.Column(db.Boolean, default=False)
upload_date = db.Column(db.DateTime, default=datetime.utcnow)
sold_date = db.Column(db.DateTime, default=None)

user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
</code></pre>
<p>This is how it is being created</p>
<pre><code>def create_db():
with app.app_context():
db.create_all()

if __name__ == '__main__':
create_db()
app.run(debug=True)
</code></pre>
<p>I get this error. Can someone help please?</p>
<pre><code>sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.trailers - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
</code></pre>
<p>I am also getting this error in my terminal when I run this python script.</p>
<p>sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'trailers.user_id' could not find table 'users' with which to generate a foreign key to target column 'id'</p>
<p>Thanks</p>
 

Latest posts

Top