SQLAlchemy 默认过滤器 [英] SQLAlchemy default filter

查看:71
本文介绍了SQLAlchemy 默认过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 is_deleted 字段的模型,现在除了传递给 .filter 和 .filter_by 的任何过滤参数之外,我还希望该模型的所有查询形式始终通过 is_deleted=False 进行过滤.

I have a model with a field is_deleted, now I want all forms of query for this model to always filter by is_deleted=False in addition to whatever filtering arguments is passed to .filter and .filter_by.

在 Django 中,我通常会覆盖管理器并添加我自己的过滤器,但我需要 SQLAlchemy 的帮助.

In Django, I would normally override the manager and add my own filtering but I need help for SQLAlchemy.

更新:

我最终做了以下事情:

class CustomQuery(Query):
    def __new__(cls, *args, **kwargs):
        if args and hasattr(args[0][0], "is_deleted"):
            return Query(*args, **kwargs).filter_by(is_deleted=False)
        else:
            return object.__new__(cls)
session = scoped_session(sessionmaker(query_cls=CustomQuery))

它有效,但如果我稍后有更多字段,我想我将不得不添加更多条件,必须有一种方法可以在模型级别执行此操作.

It works but if I have more fields later on I imagine I'll have to add more condition, there must be a way to do this on the model level.

推荐答案

这是一个非常古老的问题,所以我确信 OP 解决了他们的问题,但由于它仍未得到解答(在 2021 年)这里是我们如何处理申请所有模型的自定义查询类:

This is a very old question so I'm sure the OP solved their issue, but as it remains unanswered (in 2021) here's how we've approached applying a custom query class to all models:

  1. 如上定义自定义查询

class CustomQuery(Query): ...

  1. 然后将此查询类设置为基本模型类的查询属性:

class BaseModel(Model):
    __abstract__ = True
    query_class = CustomQuery
    ...

那么任何实现 BaseModel 的模型显然都会继承这种行为:

Then any models implementing the BaseModel will obviously inherit this behaviour:

class MyModel(BaseModel):
    __tablename__ = 'my_model' 
    ....

请注意,在我们的示例中,并非所有表都遵循软删除模式(我们不关心每个表的历史记录).在这里,您可以实现一个使用默认查询类的单独 BaseModel.

Note, in our case not all of the tables follow the soft delete pattern (we don't care about the history of every single table). Here, you could implement a separate BaseModel that uses the default query class.

class ImmutableBaseModel(Model):
    __abstract__ = True
    query_class = CustomQuery
    ...

class MutableBaseModel(Model):
    __abstract__ = True

如果您发现自己在这里并且尚未阅读它,请查看 Miguel Grinberg 撰写的关于实施 软删除模式伴随回购

If you find yourself here and you've not read it yet check out this excellent blog post from Miguel Grinberg on implementing the soft delete pattern and accompanying repo

这篇关于SQLAlchemy 默认过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆