[Flask] Establishing foreign key back to parent class
Tim Johnson
tim at akwebsoft.com
Sat Feb 13 17:47:12 EST 2016
FYI : Python coder 12 years in CGI and MySQL
new to flask and SQLAlchemy.
(have always just used MysqlDB)
Using SQLAlchemy Version 1.0.11 with python 2.7.6 on Ubuntu 14.04
I've followed a couple of "paint by numbers " tutorials from both th
M. Grinberg book and from the following URL
https://www.digitalocean.com/community/tutorials/how-to-structure-large-flask-applications
The second tutorial takes little different approach to setting up
data models, by implementing a base class for the date module.
The code in question can be found at the URL under the heading
"Step 2: Define The Module Data Model(s)"
Using that code generated an error for me -
"sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key
relationships between 'base' and 'auth_user'."
None of the comments at the URL reference the problem that I had,
Question 1 :
could that be because of a new version of SQLAlchemy?
I found my success by eliminating the Base class and moving the code
from the Base class in the User Class and using db.Model as the
parent class.
# My working code is as follows:
# Import the database object (db) from the main application module
# We will define this inside /app/__init__.py in the next sections.
from app import db # SQLAlchemy instance
# Define a base model for other database tables to inherit
# class Base(db.Model):
# __abstract_ = True
# id = db.Column(db.Integer, primary_key=True)
# date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
# date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(),
# onupdate=db.func.current_timestamp())
# Define a User model
# class User(Base):
class User(db.Model):
# The following 4 assignments are taken from the Base Class
__abstract_ = True
id = db.Column(db.Integer, primary_key=True)
date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(),
onupdate=db.func.current_timestamp())
__tablename__ = 'auth_user'
# User Name
name = db.Column(db.String(128), nullable=False)
# Identification Data: email & password
email = db.Column(db.String(128), nullable=False,
unique=True)
password = db.Column(db.String(192), nullable=False)
# Authorisation Data: role & status
role = db.Column(db.SmallInteger, nullable=False)
status = db.Column(db.SmallInteger, nullable=False)
# New instance instantiation procedure
def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = password
def __repr__(self):
return '<User %r>' % (self.name)
Question 2: What is missing from the original code using
db.Model -> Base -> User scheme?
I.E. how to establish the foreign key relationship
Thanks
--
Tim
http://www.akwebsoft.com, http://www.tj49.com
More information about the Flask
mailing list