MODEL.query.all()查询报错

来源:7-1 .管理员登录

安生ing

2017-08-08

数据库表已经生成,但是在查询的时候会提示以下错误

OperationalError: (sqlite3.OperationalError) no such table: user [SQL: 'SELECT user.id AS user_id, user.name AS user_name, user.pwd AS user_pwd, user.email AS user_email, user.phone AS user_phone, user.info AS user_info, user.face AS user_face, user.addtime AS user_addtime, user.uuid AS user_uuid \nFROM user']

执行任何一个Model,都是这个样子

写回答

5回答

rustgopy

2017-08-08

同学,你好,你把数据表的截图以及models.py截图发给我看看。

0
1
安生ing
代码太长,添加到这个问题的回复列表中了。
2017-08-08
共1条回复

安生ing

提问者

2017-08-08

In [4]: dir(Admin)
Out[4]: 
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__mapper__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__table__',
 '__table_args__',
 '__tablename__',
 '__weakref__',
 '_cached_tablename',
 '_decl_class_registry',
 '_sa_class_manager',
 'addtime',
 'adminlogs',
 'check_pwd',
 'id',
 'is_super',
 'metadata',
 'name',
 'oplogs',
 'pwd',
 'query',
 'query_class',
 'role',
 'role_id']

In [5]: dir(Admin.query)
Out[5]: 
['_Query__all_equivs',
 '__class__',
 '__clause_element__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_adapt_all_clauses',
 '_adapt_clause',
 '_adapt_col_list',
 '_adapt_polymorphic_element',
 '_adjust_for_single_inheritance',
 '_attributes',
 '_autoflush',
 '_bind_mapper',
 '_clone',
 '_compile_context',
 '_compound_eager_statement',
 '_conditional_options',
 '_connection_from_session',
 '_correlate',
 '_criterion',
 '_current_path',
 '_distinct',
 '_enable_assertions',
 '_enable_eagerloads',
 '_enable_single_crit',
 '_entities',
 '_entity_zero',
 '_execute_and_instances',
 '_execution_options',
 '_filter_aliases',
 '_for_update_arg',
 '_from_obj',
 '_from_obj_alias',
 '_from_selectable',
 '_get_bind_args',
 '_get_condition',
 '_get_existing_condition',
 '_get_impl',
 '_get_options',
 '_group_by',
 '_has_mapper_entities',
 '_having',
 '_invoke_all_eagers',
 '_join',
 '_join_entities',
 '_join_left_to_right',
 '_join_to_left',
 '_joinpath',
 '_joinpoint',
 '_joinpoint_zero',
 '_limit',
 '_mapper_adapter_map',
 '_mapper_entities',
 '_mapper_loads_polymorphically_with',
 '_mapper_zero',
 '_no_clauseelement_condition',
 '_no_criterion_assertion',
 '_no_criterion_condition',
 '_no_limit_offset',
 '_no_statement_condition',
 '_no_yield_per',
 '_offset',
 '_only_entity_zero',
 '_only_full_mapper_zero',
 '_only_load_props',
 '_options',
 '_order_by',
 '_orm_only_adapt',
 '_orm_only_from_obj_alias',
 '_params',
 '_polymorphic_adapters',
 '_populate_existing',
 '_prefixes',
 '_prepare_right_side',
 '_primary_entity',
 '_query_entity_zero',
 '_refresh_state',
 '_reset_joinpoint',
 '_reset_polymorphic_adapter',
 '_select_args',
 '_select_from_entity',
 '_set_enable_single_crit',
 '_set_entities',
 '_set_entity_selectables',
 '_set_op',
 '_set_select_from',
 '_should_log_debug',
 '_should_log_info',
 '_should_nest_selectable',
 '_simple_statement',
 '_statement',
 '_suffixes',
 '_update_joinpoint',
 '_values',
 '_version_check',
 '_with_current_path',
 '_with_hints',
 '_with_invoke_all_eagers',
 '_with_labels',
 '_with_options',
 '_yield_per',
 'add_column',
 'add_columns',
 'add_entity',
 'all',
 'as_scalar',
 'autoflush',
 'column_descriptions',
 'correlate',
 'count',
 'cte',
 'delete',
 'dispatch',
 'distinct',
 'enable_assertions',
 'enable_eagerloads',
 'except_',
 'except_all',
 'execution_options',
 'exists',
 'filter',
 'filter_by',
 'first',
 'first_or_404',
 'from_self',
 'from_statement',
 'get',
 'get_or_404',
 'group_by',
 'having',
 'instances',
 'intersect',
 'intersect_all',
 'join',
 'label',
 'limit',
 'logger',
 'merge_result',
 'offset',
 'one',
 'one_or_none',
 'options',
 'order_by',
 'outerjoin',
 'paginate',
 'params',
 'populate_existing',
 'prefix_with',
 'reset_joinpoint',
 'scalar',
 'select_entity_from',
 'select_from',
 'selectable',
 'session',
 'slice',
 'statement',
 'subquery',
 'suffix_with',
 'union',
 'union_all',
 'update',
 'value',
 'values',
 'whereclause',
 'with_entities',
 'with_for_update',
 'with_hint',
 'with_labels',
 'with_lockmode',
 'with_parent',
 'with_polymorphic',
 'with_session',
 'with_statement_hint',
 'with_transformation',
 'yield_per']

In [6]: type(Admin)
Out[6]: flask_sqlalchemy._BoundDeclarativeMeta


0
0

安生ing

提问者

2017-08-08

~/project/Curly$ pyenv activate curly 
~/project/Curly$ ipython
Python 3.6.1 (default, Jul 17 2017, 10:51:14) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from app.models import Admin,User

In [2]: Admin.query.all()
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/engine/base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1181                         parameters,
-> 1182                         context)
   1183         except BaseException as e:

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/engine/default.py in do_execute(self, cursor, statement, parameters, context)
    469     def do_execute(self, cursor, statement, parameters, context=None):
--> 470         cursor.execute(statement, parameters)
    471 

OperationalError: no such table: admin

The above exception was the direct cause of the following exception:

OperationalError                          Traceback (most recent call last)
<ipython-input-2-590c85bd87e4> in <module>()
----> 1 Admin.query.all()

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/orm/query.py in all(self)
   2701 
   2702         """
-> 2703         return list(self)
   2704 
   2705     @_generative(_no_clauseelement_condition)

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/orm/query.py in __iter__(self)
   2853         if self._autoflush and not self._populate_existing:
   2854             self.session._autoflush()
-> 2855         return self._execute_and_instances(context)
   2856 
   2857     def __str__(self):

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/orm/query.py in _execute_and_instances(self, querycontext)
   2876             close_with_result=True)
   2877 
-> 2878         result = conn.execute(querycontext.statement, self._params)
   2879         return loading.instances(querycontext.query, result, querycontext)
   2880 

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/engine/base.py in execute(self, object, *multiparams, **params)
    943             raise exc.ObjectNotExecutableError(object)
    944         else:
--> 945             return meth(self, multiparams, params)
    946 
    947     def _execute_function(self, func, multiparams, params):

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/sql/elements.py in _execute_on_connection(self, connection, multiparams, params)
    261     def _execute_on_connection(self, connection, multiparams, params):
    262         if self.supports_execution:
--> 263             return connection._execute_clauseelement(self, multiparams, params)
    264         else:
    265             raise exc.ObjectNotExecutableError(self)

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/engine/base.py in _execute_clauseelement(self, elem, multiparams, params)
   1051             compiled_sql,
   1052             distilled_params,
-> 1053             compiled_sql, distilled_params
   1054         )
   1055         if self._has_events or self.engine._has_events:

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/engine/base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1187                 parameters,
   1188                 cursor,
-> 1189                 context)
   1190 
   1191         if self._has_events or self.engine._has_events:

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/engine/base.py in _handle_dbapi_exception(self, e, statement, parameters, cursor, context)
   1400                 util.raise_from_cause(
   1401                     sqlalchemy_exception,
-> 1402                     exc_info
   1403                 )
   1404             else:

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/util/compat.py in raise_from_cause(exception, exc_info)
    201     exc_type, exc_value, exc_tb = exc_info
    202     cause = exc_value if exc_value is not exception else None
--> 203     reraise(type(exception), exception, tb=exc_tb, cause=cause)
    204 
    205 if py3k:

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/util/compat.py in reraise(tp, value, tb, cause)
    184             value.__cause__ = cause
    185         if value.__traceback__ is not tb:
--> 186             raise value.with_traceback(tb)
    187         raise value
    188 

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/engine/base.py in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1180                         statement,
   1181                         parameters,
-> 1182                         context)
   1183         except BaseException as e:
   1184             self._handle_dbapi_exception(

~/.pyenv/versions/3.6.1/envs/curly/lib/python3.6/site-packages/sqlalchemy/engine/default.py in do_execute(self, cursor, statement, parameters, context)
    468 
    469     def do_execute(self, cursor, statement, parameters, context=None):
--> 470         cursor.execute(statement, parameters)
    471 
    472     def do_execute_no_params(self, cursor, statement, context=None):

OperationalError: (sqlite3.OperationalError) no such table: admin [SQL: 'SELECT admin.id AS admin_id, admin.name AS admin_name, admin.pwd AS admin_pwd, admin.is_super AS admin_is_super, admin.role_id AS admin_role_id, admin.addtime AS admin_addtime \nFROM admin']

In [3]: User.query.all()
......

OperationalError: (sqlite3.OperationalError) no such table: user [SQL: 'SELECT user.id AS user_id, user.name AS user_name, user.pwd AS user_pwd, user.email AS user_email, user.phone AS user_phone, user.info AS user_info, user.face AS user_face, user.addtime AS user_addtime, user.uuid AS user_uuid \nFROM user']


0
0

安生ing

提问者

2017-08-08

from datetime import datetime

from app import db


class User(db.Model):  # 会员
    __tablename__ = "user"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 昵称
    pwd = db.Column(db.String(100))  # 密码
    email = db.Column(db.String(100), unique=True)  # 邮箱
    phone = db.Column(db.String(11), unique=True)  # 手机号码
    info = db.Column(db.Text)  # 个性简介
    face = db.Column(db.String(255), unique=True)  # 头像
    addtime = db.Column(db.DateTime, default=datetime.now)  # 注册时间
    uuid = db.Column(db.String(255), unique=True)  # 唯一标志符
    userlogs = db.relationship('Userlog', backref='user')  # 会员日志外键关系关联
    comments = db.relationship('Comment', backref='user')  # 评论外键关系关联
    moviecols = db.relationship('Moviecol', backref='user')  # 收藏外键关系关联

    def __repr__(self):
        return "<User %r>" % self.name

    def check_pwd(self, pwd):
        from werkzeug.security import check_password_hash
        return check_password_hash(self.pwd, pwd)


class Userlog(db.Model):  # 会员登录日志
    __tablename__ = "userlog"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属会员
    ip = db.Column(db.String(100))  # 登录IP
    addtime = db.Column(db.DateTime, default=datetime.now)  # 登录时间

    def __repr__(self):
        return "<Userlog %r>" % self.id


class Tag(db.Model):  # 标签
    __tablename__ = "tag"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 标题
    addtime = db.Column(db.DateTime, default=datetime.now)  # 添加时间
    movies = db.relationship("Movie", backref='tag')  # 电影外键关系关联

    def __repr__(self):
        return "<Tag %r>" % self.name


class Movie(db.Model):  # 电影
    __tablename__ = "movie"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    title = db.Column(db.String(255), unique=True)  # 标题
    url = db.Column(db.String(255), unique=True)  # 地址
    info = db.Column(db.Text)  # 简介
    logo = db.Column(db.String(255), unique=True)  # 封面
    star = db.Column(db.SmallInteger)  # 星级
    playnum = db.Column(db.BigInteger)  # 播放量
    commentnum = db.Column(db.BigInteger)  # 评论量
    tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'))  # 所属标签
    area = db.Column(db.String(255))  # 上映地区
    release_time = db.Column(db.Date)  # 上映时间
    length = db.Column(db.String(100))  # 播放时间
    addtime = db.Column(db.DateTime, default=datetime.now)  # 添加时间
    comments = db.relationship("Comment", backref='movie')  # 评论外键关系关联
    moviecols = db.relationship("Moviecol", backref='movie')  # 收藏外键关系关联

    def __repr__(self):
        return "<Movie %r>" % self.title


class Preview(db.Model):  # 上映预告
    __tablename__ = "preview"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    title = db.Column(db.String(255), unique=True)  # 标题
    logo = db.Column(db.String(255), unique=True)  # 封面
    addtime = db.Column(db.DateTime, default=datetime.now)  # 添加时间

    def __repr__(self):
        return "<Preview %r>" % self.title


class Comment(db.Model):  # 评论
    __tablename__ = "comment"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    content = db.Column(db.Text)  # 内容
    movie_id = db.Column(db.Integer, db.ForeignKey('movie.id'))  # 所属电影
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属用户
    addtime = db.Column(db.DateTime, default=datetime.now)  # 添加时间

    def __repr__(self):
        return "<Comment %r>" % self.id


class Moviecol(db.Model):  # 电影收藏
    __tablename__ = "moviecol"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    movie_id = db.Column(db.Integer, db.ForeignKey('movie.id'))  # 所属电影
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属用户
    addtime = db.Column(db.DateTime, default=datetime.now)  # 添加时间

    def __repr__(self):
        return "<Moviecol %r>" % self.id


class Auth(db.Model):  # 权限
    __tablename__ = "auth"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 名称
    url = db.Column(db.String(255), unique=True)  # 地址
    addtime = db.Column(db.DateTime, default=datetime.now)  # 添加时间

    def __repr__(self):
        return "<Auth %r>" % self.name


class Role(db.Model):  # 角色
    __tablename__ = "role"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 名称
    auths = db.Column(db.String(600))  # 角色权限列表
    addtime = db.Column(db.DateTime, default=datetime.now)  # 添加时间
    admins = db.relationship("Admin", backref='role')  # 管理员外键关系关联

    def __repr__(self):
        return "<Role %r>" % self.name


class Admin(db.Model):  # 管理员
    __tablename__ = "admin"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 管理员账号
    pwd = db.Column(db.String(100))  # 管理员密码
    is_super = db.Column(db.SmallInteger)  # 是否为超级管理员,0为超级管理员
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'))  # 所属角色
    addtime = db.Column(db.DateTime, default=datetime.now)  # 添加时间
    adminlogs = db.relationship("Adminlog", backref='admin')  # 管理员登录日志外键关系关联
    oplogs = db.relationship("Oplog", backref='admin')  # 管理员操作日志外键关系关联

    def __repr__(self):
        return "<Admin %r>" % self.name

    def check_pwd(self, pwd):
        from werkzeug.security import check_password_hash
        return check_password_hash(self.pwd, pwd)


class Adminlog(db.Model):  # 管理员登录日志
    __tablename__ = "adminlog"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    admin_id = db.Column(db.Integer, db.ForeignKey('admin.id'))  # 所属管理员
    ip = db.Column(db.String(100))  # 登录IP
    addtime = db.Column(db.DateTime, default=datetime.now)  # 登录时间

    def __repr__(self):
        return "<Adminlog %r>" % self.id


class Oplog(db.Model):  # 操作日志
    __tablename__ = "oplog"
    __table_args__ = {"useexisting": True}
    id = db.Column(db.Integer, primary_key=True)  # 编号
    admin_id = db.Column(db.Integer, db.ForeignKey('admin.id'))  # 所属管理员
    ip = db.Column(db.String(100))  # 登录IP
    reason = db.Column(db.String(600))  # 操作原因
    addtime = db.Column(db.DateTime, default=datetime.now)  # 登录时间

    def __repr__(self):
        return "<Oplog %r>" % self.id


if __name__ == "__main__":
    db.create_all()


0
0

安生ing

提问者

2017-08-08

用的是SQLITE数据库,但是生成表是没有问题的,

$ sqlite3 xxx.db 
SQLite version 3.16.2 2017-01-06 16:32:41
Enter ".help" for usage hints.
sqlite> .schema user
CREATE TABLE user (
        id INTEGER NOT NULL, 
        name VARCHAR(100), 
        pwd VARCHAR(100), 
        email VARCHAR(100), 
        phone VARCHAR(11), 
        info TEXT, 
        face VARCHAR(255), 
        addtime DATETIME, 
        uuid VARCHAR(255), 
        PRIMARY KEY (id), 
        UNIQUE (name), 
        UNIQUE (email), 
        UNIQUE (phone), 
        UNIQUE (face), 
        UNIQUE (uuid), 
        UNIQUE (name), 
        UNIQUE (email), 
        UNIQUE (phone), 
        UNIQUE (face), 
        UNIQUE (uuid)
);
sqlite>


0
2
安生ing
回复
rustgopy
问题解决了,把数据库换回MYSQL就好了
2017-08-08
共2条回复

Python Flask 构建微电影视频网站

Python 最好用轻量级框架,让你轻松胜任 Python Web 工程师

683 学习 · 663 问题

查看课程