有没有办法在peewee中定义自动增量场.
我知道我们可以定义序列,但需要手动创建序列而不是由create_tables管理,这阻止了我使用它.(构建过程由create tables管理,我宁愿不添加手动步骤)
import peewee
class TestModel(peewee.Model):
test_id = peewee.BigIntegerField(sequence='test_id_seq')
Run Code Online (Sandbox Code Playgroud)
替代上面的代码,我宁愿拥有.由于大多数数据库都有串行字段,因此我没有看到维持序列的要点.
import peewee
class TestModel(peewee.Model):
test_id = peewee.AutoIncremenetIntField()
Run Code Online (Sandbox Code Playgroud)
您可以使用PrimaryKeyField()评论中提到的@wyatt
或者您可以使用Playhouse-信号支持(撒尿扩展)
from playhouse.signals import Model, pre_save
class MyModel(Model):
data = IntegerField()
@pre_save(sender=MyModel)
def on_save_handler(model_class, instance, created):
# find max value of temp_id in model
# increment it by one and assign it to model instance object
next_value = MyModel.select(fn.Max(MyModel.temp_id))[0].temp_id +1
instance.temp_id = next_value
Run Code Online (Sandbox Code Playgroud)
此处给出的答案已过时,但这仍然是我的第一个 Google 搜索结果。
Peewee 有一个特殊的字段类型,用于称为AutoField的自动递增主键:
AutoField 用于标识自动递增的整数主键。如果不指定主键,Peewee 将自动创建一个名为“id”的自增主键。
查看文档。用法示例:
class Event(Model):
event_id = AutoField() # Event.event_id will be auto-incrementing PK.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2459 次 |
| 最近记录: |