Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy search function on table as classmethod?

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

results = Customer.search(query)

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

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

Can i use cls in place of DBSession.query?

DBSession.query(Customer).filter(...)
cls.query(Customer).filter(...)
like image 623
Ominus Avatar asked Jan 19 '12 21:01

Ominus


People also ask

What is __ repr __ SQLAlchemy?

The __repr__ function is defined by the designer of a type, in order to provide a means for users of the type to represent values of that type unambiguously, with a string.

What is subquery in SQLAlchemy?

The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

What is scalar subquery SQLAlchemy?

A scalar subquery is a subquery that selects only one column or expression and returns one row. A scalar subquery can be used anywhere in an SQL query that a column or expression can be used.

What is DB Create_all ()?

create_all() function to create the tables that are associated with your models. In this case you only have one model, which means that the function call will only create one table in your database: from app import db, Student.


1 Answers

To use

cls.query

you have to assign a query_property to your model classes!

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

Base.query = Session.query_property()

Then you can simply write:

cls.query.filter(...)

Note that you don't specify the Object to query for anymore, that is automatically done by using the query_property mechanism.

like image 183
moschlar Avatar answered Sep 20 '22 15:09

moschlar