Sqlalchemy search function on table as classmethod?

Assuming I have a class called Customer that is defined in sqlalchemy to represent a customer table. I want to write a search method to ...

results = Customer.search(query) 

will return results based on the method. I want to do this as an @classmethod method?

 @classmethod def search(cls,query): #do some stuff return results 

Can I use cls instead of DBSession.query?

 DBSession.query(Customer).filter(...) cls.query(Customer).filter(...) 
+4
source share
2 answers

I recently wrote some similar code following this link .

 class Users(Base): __tablename__ = 'users' @classmethod def by_id(cls, userid): return Session.query(Users).filter(Users.id==userid).first() 

So the answer to your first question seems to be yes. Not sure about the second, as I have not replaced cls for DBSession.

+4
source

To use

 cls.query 

you need to assign query_property to your model classes!

You might want to use this in other model classes as well, so you might want to do this in your base model class somewhere in your model/__init__.py :

 Base.query = Session.query_property() 

Then you can simply write:

 cls.query.filter(...) 

Note that you no longer specify the object for the query, which is automatically done using the query_property mechanism.

+8
source

Source: https://habr.com/ru/post/1391936/


All Articles