I have a Flask app with Flask-SQLAlchemy. I'm trying to make a one to many relationship from a user to a trip. I saw that, if I use the declarative_base of SQLAlchemy it works but when I use the db.Model from Flask-SQLAlchemy it dosen't work.
I'm getting the following error:
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|User|User, expression 'Trip' failed to locate a name ("name 'Trip' is not defined"). If this is a class name, consider adding this relationship() to the <class 'models.user.User'> class after both dependent classes have been defined.
Here are the models:
database.py
from flask import abort
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc
db = SQLAlchemy()
class Mixin(db.Model):
__abstract__ = True
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, default=db.func.now())
date_changed = db.Column(
db.DateTime, nullable=True, onupdate=db.func.now())
date_to = db.Column(db.DateTime, nullable=True)
user.py
from database import Mixin, db
class User(Mixin, db.Model):
__tablename__ = 'User'
trips = db.relationship(
'Trip',
backref=db.backref('user', lazy='joined'),
lazy='dynamic'
)
trip.py
from database import Mixin, db
class Trip(Mixin, db.Model):
__tablename__ = 'Trip'
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.String(250), nullable=False)
user_id = db.Column(
db.Integer,
db.ForeignKey('User.id'),
nullable=False
)
Storing all models in one file is a good idea, but only for a small number of models. For the large I would prefer to store models in semantically separate files.
models
├── __init__.py
├── model1.py
├── model2.py
└── model3.py
In the __init__.py need to import all models files
import models.model1.py
import models.model2.py
import models.model3.py
I fixed it by using one file for my models. I didn't have enough models to need multiple model files anyway.
Related
How can i link both entities with relationship with flask python?
for example i have this entity, here i am trying to link with user = relationship('User'), so i am getting error relation of relationship (btw: Grant, User, Client are in differents files )
from sqlalchemy.orm import relationship
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Grant(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(
db.Integer, db.ForeignKey('user.id', ondelete='CASCADE')
)
user = relationship('User')
this is the error:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Grant->grant, expression 'User' failed to locate a name ('User'). If this is a class name, consider adding this relationship() to the <class 'model.Grant.Grant'> class after both dependent classes have been defined.
note: those are my anothers entities:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True, index=True,
nullable=False)
def check_password(self, password):
return True
and this is the Client.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Client(db.Model):
name = db.Column(db.String(40))
client_id = db.Column(db.String(40), primary_key=True)
this is the error user = relationship('User') please helpme
I have a problem creating relationships between my tables in flask-sqlalchemy. I have a table with project overview, and from there on out I want to dynamically create new experiment tables with a relationship to my project overview. However, when I try to define the relationship, sqlalchemy throws the following error:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Projects->projects, expression 'Experiment_Overview' failed to locate a name ('Experiment_Overview'). If this is a c
lass name, consider adding this relationship() to the <class 'app.Projects'> class after both dependent classes have been defined.
This seems to be the case because the class Experiment_Overview(db.Model) does not exist yet, which is correct since it will be dynamically generated later on through user input. How can I mitigate this error?
import os
from flask import Flask, render_template, redirect, request, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
Bootstrap(app)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///DATA/DB.db"
db = SQLAlchemy(app)
def TableCreator(tablename):
class Experiment_Overview(db.Model):
__tablename__ = tablename
creation_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
experiment_name = db.Column(db.String(30), unique=False, nullable=False, primary_key=True)
projectname = db.Column(db.String(150), db.ForeignKey('projects.projectname'), nullable=False, unique=True)
return MyTable
class Projects(db.Model):
projectname = db.Column(db.String(150), unique=True, nullable=False, primary_key=True)
creation_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
experiments = db.relationship('Experiment_Overview', backref="experiments", lazy=True, uselist=False)
def __init__(self, owner, projectname, status, created_at):
self.owner=owner
self.projectname=projectname
self.status=status
self.created_at=created_at
db.create_all()
Generally speaking, you don't dynamically create tables; you usually shouldn't create or drop tables while your program is running.
Additionally, I believe it's impossible to create a true relationship that links back to an entire table. Relationships/Foreign Keys are for linking between rows in tables.
Don't worry, there are easier ways to achieve the behavior that you are looking for here.
From your question it sounds like you can have multiple Projects, and each project can have multiple Experiments within the project.
This would make the relationship between a Project and its Experiments a One-To-Many relationship.
If this is the case, you would need one Projects table (which you have already in your code), and you would also have one Experiments table.
Each row in the Projects table represents one Project.
Each row in the Experiments table represents one Experiment. The Experiments table will have a column containing a foreign key linking back to the Project the Experiment is linked to.
I've modified your code according to the One-To-Many example code given in the SQLAlchemy documentation that I linked above.
Note the addition of the back_populates option to the relationship(), this allows bi-directional knowledge of the relationship: the Experiment know what project it belongs to, and the Project know what Experiments it has.
import os
from flask import Flask, render_template, redirect, request, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
Bootstrap(app)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///DATA/DB.db"
db = SQLAlchemy(app)
class Projects(db.Model):
__tablename__ = "projects"
projectname = db.Column(db.String(150), unique=True, nullable=False, primary_key=True)
creation_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
experiments = db.relationship("Experiment", back_populates="project")
def __init__(self, owner, projectname, status, created_at):
self.owner=owner
self.projectname=projectname
self.status=status
self.created_at=created_at
class Experiment(db.Model):
__tablename__ = "experiments"
creation_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
experiment_name = db.Column(db.String(30), unique=False, nullable=False, primary_key=True)
projectname = db.Column(db.String(150), db.ForeignKey('projects.projectname'), nullable=False)
project = relationship("Project", back_populates="experiments")
db.create_all()
I am a beginner with SQLAlchemy and I just did my first modules.py file for a Flask application. However, in the main app, when I try to create two objects of type user :
from models import user_presence,User,Activity_Presence
db.create_all()
u1 = User()
u2 = User()
I get the error that: sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'activity_presence' and 'User_Presence'. I tried following the official tutorials, but I don't understand why there is an issue with the foreign key relationship. I also tried adding more fields, adding objects to the relationship, but I just can't figure out what the problem is. If you have any idea I would be very thankful. Sorry if the question is too much of a beginner one.
from api import db
user_presence = db.Table('User_Presence',
db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
db.Column('presence_id', db.Integer, db.ForeignKey('Activity_Presence.id'), primary_key=True)
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
presence_activ= db.relationship('Activity_Presence', secondary=user_presence, lazy='subquery',
backref=db.backref('users', lazy=True))
class Activity_Presence(db.Model):
id = db.Column(db.Integer, primary_key=True)
The error lies in the reference to the wrong table name.
The usual naming of the classes that represent the model is done in camelcase. This name is then converted to snakecase to provide the table name. If you should use an underscore in your class name, it will be retained and another one will be added for any subsequent capital letters.
As an an example:
class ActivityPresence(db.Model):
__tablename__ = 'activity_presence'
class Activity_Presence(db.Model):
__tablename__ = 'activity__presence'
So the working code is as follows.
user_presence = db.Table('user_presence',
db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
db.Column('presence_id', db.Integer, db.ForeignKey('activity_presence.id'), primary_key=True)
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
presence_activ= db.relationship('ActivityPresence',
secondary=user_presence,
lazy='subquery',
backref=db.backref('users', lazy=True))
class ActivityPresence(db.Model):
id = db.Column(db.Integer, primary_key=True)
I have been fighting this error for a few days now in a variety of configurations.
I tried adding Relationship lines under each of the ForeignKeys with no luck.
I also swapped my queries from using the declarative_base style calls to SQL queries.
The error only appears once I add the second ForeignKey to Task. (I originally had several foreign keys in Task and Project but pared things down until it worked and tried slowly adding things back. Adding the second ForeignKey did it no matter which table it was added to.)
My current Flask method is:
#app.route('/project/<int:project_id>/')
def showProject(project_id):
project = session.query(Project).from_statement(text("SELECT * FROM project WHERE project.id = project_id ORDER BY project.projnum DESC"))
tasks = session.query(Task).filter_by(project_id = project_id).all()
return render_template('project.html', project = project, tasks = tasks)
And I get a "no such column" error:
OperationalError: (sqlite3.OperationalError) no such column: task.project_id [SQL: u'SELECT task.id AS task_id, task.name AS task_name, task.description AS task_description, task.assigned_id AS task_assigned_id, task.project_id AS task_project_id, task.due AS task_due \nFROM task \nWHERE task.project_id = ?'] [parameters: (2,)]
This is the setup file for my database:
import os
import sys
import time
from sqlalchemy import Column, ForeignKey, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
engine = create_engine('sqlite:///gmnpm.db')
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
email = Column(String(250), nullable=False)
picture = Column(String(250))
class Task(Base):
__tablename__ = 'task'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
description = Column(String(2000))
assigned_id = Column(Integer, ForeignKey('user.id'))
project_id = Column(Integer, ForeignKey('project.id'))
due = Column(Integer, default=int(time.time()))
class Project(Base):
__tablename__ = 'project'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
description = Column(String(1000))
projnum = Column(Integer)
Base.metadata.create_all(engine)
After reading a bunch of documentation and going crazy trying random things on the off chance they work, I'm grateful for any suggestions!
related to this question: SQLAlchemy logging of changes with date and user
I'm using a modified version of the "recipe" for versioning changes automatically. I think it's able to handle some forms of relationships already (not sure, though), but I'm not able to handle the case where there's a many-to-many relationship in a separate table.
Here's a simple example that's an issue:
from history_meta import (Versioned, versioned_session)
Base = declarative_base()
user_to_group = Table('user_to_group', Base.metadata,
Column('user_login', String(60), ForeignKey('user.login')),
Column('group_name', String(100), ForeignKey('group.name'))
)
class User(Versioned, Base):
__tablename__ = 'user'
login = Column(String(60), primary_key=True, nullable=False)
password = Column(BINARY(20), nullable=False)
class Group(Versioned, Base):
__tablename__ = 'group'
name = Column(String(100), primary_key=True, nullable=False)
description = Column(String(100), nullable=True)
users = relationship(User, secondary=user_to_group, backref='groups')
When generating the tables in the database with Base.metadata.create_all(engine) I can see that there are only 5 tables: user, group, user_to_group, user_history, and group_history There is no user_to_group_history.
The "versioning" gets added to the declarative objects through inheritance of Versioned, but there's no way (that I can see) to do something similar with the user_to_group table which isn't using the declarative format. There's also notes in the documentation saying that it's not a good idea using a table that's mapped to a class so I'm trying to avoid using a declarative object for the relationship.