【问题标题】:Pylons, SQlite and autoincrementing fieldsPylons、SQlite 和自动增量字段
【发布时间】:2011-06-01 20:10:35
【问题描述】:

嘿! 刚开始使用 Pylons 和 SQLAlchemy,我的模型看起来像这样:

from sqlalchemy import Column
from sqlalchemy.types import Integer, String

from helloworld.model.meta import Base

class Person(Base):
    __tablename__ = "person"

    id = Column(Integer, primary_key=True)
    name = Column(String(100))
    email = Column(String(100))

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

    def __repr__(self):
        return "<Person('%s')" % self.name

为避免 sqlite 重用可能已删除的 id,我想将 AUTOINCREMENT 添加到“id”列。我查看了 sqlalchemy 的文档,发现可以发出 sqlite_autoincrement。 可以找到给出此属性的示例here

sqlite_autoincrement 似乎是在创建表本身时发出的,我只是想知道在使用诸如我的模型的声明式样式时如何提供它。

【问题讨论】:

    标签: sqlite sqlalchemy pylons auto-increment


    【解决方案1】:

    尝试将__table_args__ 属性与您将传递给Table 构造函数的参数包含在传统(非声明性)数据定义样式中,例如:

    class Person(Base):
        __tablename__ = "person"
        __table_args__ = {'sqlite_autoincrement': True}
    

    如果您必须包含多个参数,请改用此形式(dict 必须放在最后):

    __table_args__ = (
        Unique('foo'),
        # ...
        {'sqlite_autoincrement': True}
    )
    

    来自声明性 SQLAlchemy 文档的 Table configuration 部分:

    名称、元数据和映射的Column 参数以外的表参数是使用__table_args__ 类属性指定的。此属性同时容纳通常发送到Table 构造函数的位置参数和关键字参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多