gpt4 book ai didi

mysql - 使用非 SQLAlchemy 创建的表的外键创建模型

转载 作者:行者123 更新时间:2023-12-04 08:30:35 25 4
gpt4 key购买 nike

我的 flask 应用程序有一个我使用 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 中创建包含此类外键的表?

最佳答案

您可以使用 SQLAlchemy 的 reflection创建 Table 的能力现有类的实例,然后将该实例分配给模型的 __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
现在 MyTable可以从 OAuth2Client 中成功引用模型。

关于mysql - 使用非 SQLAlchemy 创建的表的外键创建模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65045037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com