17

当我尝试向 python/flask 添加新表时 -

class UserRemap(db.Model):
    name = db.Column(db.String(40))
    email = db.Column(db.String(255))
    password = db.Column(db.String(64))
    flag = db.Column(db.String(1))

    def __init__(self, name, email, password):
        self.email = email
        self.name = name
        self.password = password
        self.flag='N'

这是表模式 -

mysql> desc UserRemap;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| name     | varchar(40)  | NO   |     | NULL    |       |
| password | varchar(64)  | NO   |     | NULL    |       |
| email    | varchar(255) | NO   |     | NULL    |       |
| flag     | char(1)      | NO   |     | N       |       |
+----------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

当我进入交互式 python shell 并from myapp import db ;收到此错误消息时,

from server import db; Traceback (most recent call last):   File
"<stdin>", line 1, in <module>   File "server.py", line 74, in
<module>
        class UserRemap(db.Model): 
  File "/usr/lib/python2.7/site-packages/Flask_SQLAlchemy-0.15-py2.7.egg/flaskext/sqlalchemy.py",
 line 467, in __init__
     DeclarativeMeta.__init__(self, name, bases, d)  
 File "/usr/lib/python2.7/site-packages/SQLAlchemy-0.7.5-py2.7-linux-i686.egg/sqlalchemy/ext/declarative.py",
 line 1336, in __init__
     _as_declarative(cls, classname, cls.__dict__) 
  File "/usr/lib/python2.7/site-packages/SQLAlchemy-0.7.5-py2.7-linux-i686.egg/sqlalchemy/ext/declarative.py",
 line 1261, in _as_declarative
     "table-mapped class." % cls sqlalchemy.exc.InvalidRequestError: Class <class 'server.UserRemap'> does not have a __table__ or
 __tablename__ specified and does not inherit from an existing table-mapped class.

关于如何解决这个问题的任何想法

4

3 回答 3

97

根据继承自的Flask-SQLAlchemy 文档db.Model,将自动为您设置表名。

您看到此消息是因为您没有为该表定义主键。该错误消息没有帮助,但添加主键将解决此问题。

于 2013-01-30T02:44:52.657 回答
22

您必须提及__tablename____table__通知 sqlalchemy 以获取数据库中的表。

class UserRemap(db.Model):
    __tablename__ = 'UserRemap'
    name = db.Column(db.String(40))
    email = db.Column(db.String(255))
    password = db.Column(db.String(64))
    flag = db.Column(db.String(1))

    def __init__(self, name, email, password):
        self.email = email
        self.name = name
        self.password = password
        self.flag='N'
于 2012-03-12T06:09:02.430 回答
4

__tablename__在您的类定义中指定。

class UserRemap(db.Model):
    __tablename__ = 'UserRemap'
    name = db.Column(db.String(40))
    email = db.Column(db.String(255))
于 2012-03-12T06:08:40.837 回答