使用非 SQLAlchemy 创建的 table 的外键创建模型
Create a model with a foreign key to a table not created by SQLAlchemy
我的 Flask 应用有一个 table 是我使用 mysqlconnector 创建的:
import mysql.connector
from .config import host, user, passwd, db_name
connection_pool = mysql.connector.pooling.MySQLConnectionPool(
pool_size=8,
host=host,
user=user,
password=passwd,
database=db_name)
connection_object = connection_pool.get_connection()
cursor = connection_object.cursor(buffered=True)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS MyTable (
ID INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL UNIQUE
)"""
connection_object.commit()
我正在导入的库 (authlib) 使用 SQL
连接到同一个数据库
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from authlib.integrations.sqla_oauth2 import OAuth2ClientMixin
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://user:pwd@host/db'
db = SQLAlchemy (app)
class OAuth2Client(db.Model, OAuth2ClientMixin):
__tablename__ = 'oauth2_client'
id = db.Column(db.Integer, primary_key=True)
smthg_id = db.Column(
db.Integer, db.ForeignKey('MyTable.id', ondelete='CASCADE'))
smthg = db.relationship('MyTable')
client = OAuth2Client()
db.session.add (client)
db.session.commit()
在执行过程中,它引发了这个错误:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class OAuth2Client->oauth2_client, expression 'MyTable' failed to locate a name ("name 'MyTable' is not defined"). If this is a class name, consider adding this relationship() to the <class '__main__.OAuth2Client'> class after both dependent classes have been defined.
如何在 SQL Alchemy 中创建包含此类外键的 table?
您可以将 SQLAlchemy 的 reflection capabilities to create a Table 实例用于现有 class,然后将该实例分配给模型的 __table__
属性:
import sqlalchemy as sa
...
# Load the existing table into the db object's metadata
mytable = sa.Table('MyTable', db.metadata, autoload_with=db.engine)
# Create a model over the table.
class MyTable(db.Model):
__table__ = mytable
现在可以从 OAuth2Client
模型中成功引用 MyTable
。
我的 Flask 应用有一个 table 是我使用 mysqlconnector 创建的:
import mysql.connector
from .config import host, user, passwd, db_name
connection_pool = mysql.connector.pooling.MySQLConnectionPool(
pool_size=8,
host=host,
user=user,
password=passwd,
database=db_name)
connection_object = connection_pool.get_connection()
cursor = connection_object.cursor(buffered=True)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS MyTable (
ID INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL UNIQUE
)"""
connection_object.commit()
我正在导入的库 (authlib) 使用 SQL
连接到同一个数据库from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from authlib.integrations.sqla_oauth2 import OAuth2ClientMixin
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://user:pwd@host/db'
db = SQLAlchemy (app)
class OAuth2Client(db.Model, OAuth2ClientMixin):
__tablename__ = 'oauth2_client'
id = db.Column(db.Integer, primary_key=True)
smthg_id = db.Column(
db.Integer, db.ForeignKey('MyTable.id', ondelete='CASCADE'))
smthg = db.relationship('MyTable')
client = OAuth2Client()
db.session.add (client)
db.session.commit()
在执行过程中,它引发了这个错误:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class OAuth2Client->oauth2_client, expression 'MyTable' failed to locate a name ("name 'MyTable' is not defined"). If this is a class name, consider adding this relationship() to the <class '__main__.OAuth2Client'> class after both dependent classes have been defined.
如何在 SQL Alchemy 中创建包含此类外键的 table?
您可以将 SQLAlchemy 的 reflection capabilities to create a Table 实例用于现有 class,然后将该实例分配给模型的 __table__
属性:
import sqlalchemy as sa
...
# Load the existing table into the db object's metadata
mytable = sa.Table('MyTable', db.metadata, autoload_with=db.engine)
# Create a model over the table.
class MyTable(db.Model):
__table__ = mytable
现在可以从 OAuth2Client
模型中成功引用 MyTable
。