SQLAlchemy 中具有自定义逻辑的自动递增属性
我有一个简单的“发票”类,其中包含一个“Number”属性,该属性必须 当用户保存发票时由应用程序分配。 那里 有一些限制:
1)应用程序是一个(瘦)客户端-服务器应用程序,所以无论如何 分配数字时必须注意碰撞
2)发票也有一个“版本”属性,所以我不能使用简单的 DBMS 级自动增量字段
我正在尝试使用自定义类型来构建它,该类型将在每个 保存发票的时间。 每当 process_bind_param 被调用时 None 值,它将调用某种类型的单例来确定 数量并避免碰撞。 这是一个不错的解决方案吗? 不管怎样,我遇到了问题..这是我的自定义类型:
class AutoIncrement(types.TypeDecorator):
impl = types.Unicode
def copy(self):
return AutoIncrement()
def process_bind_param(self, value, dialect):
if not value:
# Must find next autoincrement value
value = "1" # Test value :)
return value
我现在的问题是,当我保存发票和自动增量时 将“1”设置为其编号值,Invoice 实例不会得到 更新了新号码..这是预期的吗? 我失踪了吗 某物? 非常感谢您抽出时间!
(Python 2.6 上的 SQLA 0.5.3,使用 postgreSQL 8.3)
编辑:Michael Bayer 告诉我这种行为是预期的,因为 TypeDecorators 不处理默认值。
I have a simple "Invoices" class with a "Number" attribute that has to
be assigned by the application when the user saves an invoice. There
are some constraints:
1) the application is a (thin) client-server one, so whatever
assigns the number must look out for collisions
2) Invoices has a "version" attribute too, so I can't use a simple
DBMS-level autoincrementing field
I'm trying to build this using a custom Type that would kick in every
time an invoice gets saved. Whenever process_bind_param is called with
a None value, it will call a singleton of some sort to determine the
number and avoid collisions. Is this a decent solution?
Anyway, I'm having a problem.. Here's my custom Type:
class AutoIncrement(types.TypeDecorator):
impl = types.Unicode
def copy(self):
return AutoIncrement()
def process_bind_param(self, value, dialect):
if not value:
# Must find next autoincrement value
value = "1" # Test value :)
return value
My problem right now is that when I save an Invoice and AutoIncrement
sets "1" as value for its number, the Invoice instance doesn't get
updated with the new number.. Is this expected? Am I missing
something?
Many thanks for your time!
(SQLA 0.5.3 on Python 2.6, using postgreSQL 8.3)
Edit: Michael Bayer told me that this behaviour is expected, since TypeDecorators don't deal with default values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是否有任何特殊原因不在列定义中使用
default=
参数? (这可以是任意 Python 可调用)。Is there any particular reason you don't just use a
default=
parameter in your column definition? (This can be an arbitrary Python callable).