Peewee中的自动增量字段

时间:2016-05-09 16:29:44

标签: 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() 

2 个答案:

答案 0 :(得分:5)

你可以使用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

答案 1 :(得分:0)

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

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

  

AutoField用于标识自动递增的整数主变量   键。如果您未指定主键,Peewee将自动   创建一个名为“ id”的自动递增主键。

看看documentation。用法示例:

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