Peewee中的自动增量字段

auto increment field in Peewee

有没有办法在peewee中定义自增字段

我知道我们可以定义序列,但需要手动创建序列而不是由 create_tables 管理,这让我无法使用它。 (构建过程由创建表管理,我不希望添加手动步骤)

import peewee
class TestModel(peewee.Model):
    test_id = peewee.BigIntegerField(sequence='test_id_seq')

我宁愿使用上述代码的替代方法。由于大多数数据库都有序列字段,所以我没有看到维护序列的意义。

import peewee
class TestModel(peewee.Model):
    test_id = peewee.AutoIncremenetIntField() 

或者你可以使用 PrimaryKeyField() 作为 @wyatt 在评论

中提到的

或者您可以使用 Playhouse- Signal Support (peewee extensions)

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

此处给出的答案已过时,但这仍然是我的第一个 Google 搜索结果。

Peewee 有一个用于自动递增主键的特殊字段类型,称为 AutoField

The AutoField is used to identify an auto-incrementing integer primary key. If you do not specify a primary key, Peewee will automatically create an auto-incrementing primary key named “id”.

看看documentation。用法示例:

class Event(Model):
  event_id = AutoField()  # Event.event_id will be auto-incrementing PK.