gpt4 book ai didi

python - 已为此 MetaData 实例定义表 'roles_users'

转载 作者:太空狗 更新时间:2023-10-29 17:19:28 26 4
gpt4 key购买 nike

我试图在我的 View 中获取 current_user 信息,我包括 from users.models import *

然后在我的代码中返回current_user;

@app.route('/panel')
@login_required
def access_panel():
return current_user.email;

一旦我运行我的服务器,它会说:

Traceback (most recent call last):
File "manage.py", line 6, in <module>
from nadel import app
File "/Users/tbd/Desktop/Projects/nadel/__init__.py", line 27, in <module>
from users import views
File "/Users/tbd/Desktop/Projects/nadel/users/views.py", line 5, in <module>
from users.models import *
File "/Users/tbd/Desktop/Projects/nadel/users/models.py", line 8, in <module>
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 67, in _make_table
return sqlalchemy.Table(*args, **kwargs)
File "/Library/Python/2.7/site-packages/sqlalchemy/sql/schema.py", line 398, in __new__
"existing Table object." % key)
sqlalchemy.exc.InvalidRequestError: Table 'roles_users' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

在我的模型中我有:

from nadel import db
from flask.ext.security import UserMixin, RoleMixin

# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))

class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))

class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
name = db.Column(db.String(255))
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
#confirmed_at = db.Column(db.DateTime())
last_login_at = db.Column(db.DateTime())
current_login_at = db.Column(db.DateTime())
last_login_ip = db.Column(db.String(32))
current_login_ip = db.Column(db.String(32))
login_count = db.Column(db.Integer)

roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))

我不明白为什么会出现此错误以及如何解决。

最佳答案

尝试添加:

__table_args__ = {'extend_existing': True}

__tablename__ 的正下方

引用:https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html?highlight=table_args

关于python - 已为此 MetaData 实例定义表 'roles_users',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908767/

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