0

我创建了一个非常简单的数据库,sqlalchemy如下所示:

from sqlalchemy import Column, Integer, String                                                                                                                                           
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine

from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Person(Base): 
    __tablename__ = 'person'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

engine = create_engine('sqlite:///sqlalchemy_example.db')

# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)

Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

# Insert a Person in the person table
new_person = Person(name='new person')
session.add(new_person)
session.commit()

然后我尝试使用pyDAL reference阅读它。

from pydal import DAL, Field
db = DAL('sqlite://sqlalchemy_example.db', auto_import=True)
db.tables
>> []
db.define_table('person', Field('name'))
>> OperationalError: table "person" already exists

如何使用 pyDAL 访问表?

谢谢你

4

1 回答 1

2

首先,不要设置auto_import=True,因为这仅在表存在 pyDAL *.table 迁移元数据文件时才相关,这里不会出现这种情况。

其次,pyDAL 不知道表已经存在,并且由于默认启用迁移,它会尝试创建表。为了防止这种情况,您可以简单地禁用迁移:

# Applies to all tables.
db = DAL('sqlite://sqlalchemy_example.db', migrate_enabled=False)

或者:

# Applies to this table only.
db.define_table('person', Field('name'), migrate=False)

如果您希望 pyDAL 为该表的未来更改接管迁移,那么您应该运行“假迁移”,这将导致 pyDAL 为该表生成一个 *.table 迁移元数据文件,而无需实际运行迁移。为此,请暂时进行以下更改:

db.define_table('person', Field('name'), fake_migrate=True)

在为单个请求保留上述内容后,将生成 *.table 文件,您可以删除该fake_migrate=True参数。

最后,请注意 pyDAL 期望该id字段是一个自动递增的整数主键字段。

于 2018-08-28T13:45:26.160 回答