联接继承中父模型上的 SQLAlchemy 'after_insert'事件



我开始摆弄SQLAlchemy才有一段时间。我正在构建一个应用程序,其中有不同类型的用户,每个具有不同的属性。因此,我构建了一个基本User模型,并使用联合继承创建了所有其他用户模型。

用户模型

class User(UserMixin, BaseModel):
__tablename__ = "users"
id = Column(Integer, primary_key=True, autoincrement=True, unique=True)
email = Column(String, unique=True, nullable=False, index=True)
confirmed = Column(Boolean, default=False, nullable=False)
role = Column(Enum(Role))
__mapper_args__ = {
"polymorphic_on": role,
}

我创建了角色作为Enum模型

class Role(enum.Enum):

admin = 1
client = 2
brand = 3
merchant = 4
customer = 5
client_user = 6
brand_user = 7
merchant_user = 8
anonymous = 9

其他用户模型有:

class Client(User):
__tablename__ = "clients"
id = Column(Integer, ForeignKey("users.id"), primary_key=True)
__mapper_args__ = {
"polymorphic_identity": "client",
'inherit_condition': (id == User.id)
}
client_data = (...)
.....

class Brand(User):
__tablename__ = "brands"

id = Column(Integer, ForeignKey("users.id"), primary_key=True)
__mapper_args__ = {
"polymorphic_identity": "brand",
'inherit_condition': id == User.id
}
brand_data = (...)
.....

在此之前一切都按照计划进行。我已经在基本用户模型上创建了一个'after_insert'事件钩子

@event.listens_for(User, "after_insert")
def dispatch_confirmation_mail(mapper, connection, target):
if not target.confirmed:
_create_reauth_mail(target.email)

现在我面临的问题是:

  1. 当我创建一个基本的用户对象的函数挂钩"after_insert"触发,但当我创建子User
  2. 查询User.query.filter_by(email=email).first()时抛出以下错误AssertionError: No such polymorphic_identity <Role.client: 2> is defined

谁能指点我一下?

我认为第一个问题的解决方案是将propagate=True添加到listens_for装饰器中,因此它变成:

@event.listens_for(User, "after_insert", propagate=True)

这确保事件侦听器传播到子类。

最新更新