简单的 Peewee ORM Python 错误 - 保存挂钩

Simple Peewee ORM Python Bug - save hook

我正在使用 Playhouse extension for Peewee,特别是信号,这样我就可以使用 @pre_save@post_save 挂钩。

我按照文档中的说明配置了它,但由于某些原因,仍然会抛出异常。


代码摘录:

from playhouse.signals import pre_save
from db.config import BaseModel

class Card(BaseModel):
    name = CharField(max_length=18)
    slug = CharField(max_length=18)
    published = BooleanField(default=False)
    category = ForeignKeyField(Category, backref='cards')


@pre_save(sender=Card)
def card_pre_save(model, instance, created):
    print('testing hook')
    if created:
        instance.slug = slugify(instance.name)

我正在这样创建一个实例:

from db import models as m

card = m.Card(
    name=new_card_name,
    category=category,
    published=False
)
card.save()

And this is the error I'm getting:
peewee.IntegrityError: null value in column "slug" violates not-null constraint
DETAIL:  Failing row contains (2, 2019-02-04 05:41:57.111115, 2019-02-04 05:41:37.75196, cool11, null, f, 2).

如果我在挂钩中填充 slug 字段,我不明白如何获得 IntegrityError。另一个问题是,甚至 pre_save 挂钩中的 print() 语句也不是 运行。

无论如何我可能会设置错误吗?

您确定您的 BaseModel 继承了 signals.Model class 吗?

http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#signals

To use the signals, you will need all of your project’s models to be a subclass of playhouse.signals.Model, which overrides the necessary methods to provide support for the various signals.