Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask SQLAlchemy - StaticMethod vs Custom Querying Class

I have an Event Model with both start_date and due_date columns. I want to create an easy way to get all active events (which have been already started but not finished yet).

This is my Event model class:

class Event(db.Model):
    __tablename__ = 'events'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(254))
    description = db.Column(db.Text)
    start_date = db.Column(db.DateTime)
    due_date = db.Column(db.DateTime)

I familiar with two working solutions for this need:

1: With a staticmethod function which will make all filters on the Event.query object and return a complete list of active events

class Event(BaseModel):
    ...
    @staticmethod
    def get_active():
         return Event.query.filter(...).all()

# Usage:
records = Event.get_active()

2: By creating a new query object that inherits from BaseQuery, and assign this new "EventQuery" class to the Model's query_class member.

class EventQuery(BaseQuery):
    def get_active(self):
        return self.filter(...)

class Event(BaseModel):
    __tablename__ = 'events'
    query_class = EventQuery
    ....

# Usage:
Event.query.get_active().all()

So I'm wondering, which method is better/recommended ?

like image 992
AlonP Avatar asked Aug 25 '17 18:08

AlonP


People also ask

What does SQLAlchemy all () return?

It does return an empty list.

What does flask SQLAlchemy query return?

Flask-SQLAlchemy Query Returns the Database Class and the Data.

What is the difference between flask SQLAlchemy and SQLAlchemy?

One of which is that Flask-SQLAlchemy has its own API. This adds complexity by having its different methods for ORM queries and models separate from the SQLAlchemy API. Another disadvantage is that Flask-SQLAlchemy makes using the database outside of a Flask context difficult.

Is flask SQLAlchemy ORM?

Flask SQLAlchemy is an ORM tool which establishes the relationship between the objects and the tables of the relational databases.


1 Answers

For a simple isolated example I don't think it matters much. For larger more complex cases, option 2 offers additional flexibility to combine your filter with other filters.

Event.query.filter_by(user_id=1).get_active().all()

Admittedly you could modify option 1 so that it takes a query as an argument and returns a new query, but then it would start looking rather different than typical SQLAlchemy queries.

like image 85
swehren Avatar answered Nov 15 '22 00:11

swehren