SQLAlchemy - can you add custom methods to the query object?

后端 未结 3 556
花落未央
花落未央 2020-12-05 13:41

Is there a way to create custom methods to the query object so you can do something like this?

User.query.all_active()

Where all_acti

3条回答
  •  不知归路
    2020-12-05 14:08

    this work for me finely

    class ParentQuery(Query):
        def _get_models(self):     
            if hasattr(query, 'attr'):
                return [query.attr.target_mapper]
            else:
                return self._mapper_zero().class_
    
        def FilterByCustomer(self):
            model_class = self._get_models()
            return self.filter(model_class.customerId == int(g.customer.get('customerId')))
    
    
    class AccountWorkflowModel(db.Model):
        query_class = ParentQuery
        .................
    

提交回复
热议问题