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 ?
It does return an empty list.
Flask-SQLAlchemy Query Returns the Database Class and the Data.
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.
Flask SQLAlchemy is an ORM tool which establishes the relationship between the objects and the tables of the relational databases.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With