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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With