我一直在观看一些视频和阅读各种帖子,试图在python脚本中理解SQLAlchemy的基本结构。
任何人都可以告诉我:
脚本:
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Records(Base):
__tablename__ = 'records'
data1 = Column(Text())
data2 = Column(Text())
data3 = Column(Text())
data4 = Column(Text())
if __name__ == "__main__":
engine = create_engine('mysql://user:password@localhost/database')
Base.metadata.create_all(bind=engine, checkfirst=True)
失败
Traceback (most recent call last):
File "sqltest.py", line 6, in <module>
class Records(Base):
File "build/bdist.linux-x86_64/egg/sqlalchemy/ext/declarative/api.py", line 55, in __init__
File "build/bdist.linux-x86_64/egg/sqlalchemy/ext/declarative/base.py", line 88, in _as_declarative
File "build/bdist.linux-x86_64/egg/sqlalchemy/ext/declarative/base.py", line 103, in setup_mapping
File "build/bdist.linux-x86_64/egg/sqlalchemy/ext/declarative/base.py", line 135, in __init__
File "build/bdist.linux-x86_64/egg/sqlalchemy/ext/declarative/base.py", line 138, in _early_mapping
File "build/bdist.linux-x86_64/egg/sqlalchemy/ext/declarative/base.py", line 530, in map
File "<string>", line 2, in mapper
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/mapper.py", line 629, in __init__
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/mapper.py", line 1223, in _configure_pks
sqlalchemy.exc.ArgumentError: Mapper Mapper|Records|records could not assemble any primary key columns for mapped table 'records'
我被迫使用主键吗?或者这与我调用记录类的方式有关吗?
答案 0 :(得分:1)
由于错误消息表明主键是必需的。没有理由不提供任何一个,否则你将无法表达任何表关系。
回应你的评论: 如果您依赖于使用缺少主键的现有数据库方案,您可以尝试zzzeek(SQLAlchemy的作者)在他对此问题的评论中提出的内容:SQLAlchemy declarative: table without any primary keys?,因此使用例如
__mapper_args__ = {"primary_key":(data1, data2)}}
if(data1,data2)标识表行。并且应该有一种方法来识别表格行,否则你会遇到严重的设计问题。
答案 1 :(得分:0)
感谢核子,我将Class移动到这个primary_key类,并指定data1列是一个长度为17的String,以便它成为主键。
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Records(Base):
__tablename__ = 'records'
data1 = Column(String(17), primary_key=True)
data2 = Column(Text())
data3 = Column(Text())
data4 = Column(Text())
if __name__ == "__main__":
engine = create_engine('mysql://user:passwd@localhost/database')
Base.metadata.create_all(bind=engine, checkfirst=True)