Apply a global filter to all tables for every query in SQLAlchemy

后端 未结 1 1905
日久生厌
日久生厌 2021-01-13 02:58

We are trying to setup a SaaS service that supports multi-tenancy in a shared database and schema. What we are planning is to have a tenant_id column on all our tables. what

相关标签:
1条回答
  • 2021-01-13 02:59

    This is outlined in the usage recipes wiki, reproduced here:

    from sqlalchemy.orm.query import Query
    
    class LimitingQuery(Query):
    
        def get(self, ident):
            # override get() so that the flag is always checked in the 
            # DB as opposed to pulling from the identity map. - this is optional.
            return Query.get(self.populate_existing(), ident)
    
        def __iter__(self):
            return Query.__iter__(self.private())
    
        def from_self(self, *ent):
            # override from_self() to automatically apply
            # the criterion too.   this works with count() and
            # others.
            return Query.from_self(self.private(), *ent)
    
        def private(self):
            mzero = self._mapper_zero()
            if mzero is not None:
                crit = mzero.class_.public == True
    
                return self.enable_assertions(False).filter(crit)
            else:
                return self
    

    The idea is to apply the filter on demand, when the query object is iterated through.

    If you want the filter to be applied to relationships as well, you'll need to use this recipe instead.

    0 讨论(0)
提交回复
热议问题