E
E
Eugene2021-01-27 14:52:38
Flask
Eugene, 2021-01-27 14:52:38

How to implement compound filters in flask-sqlalchemy?

Good afternoon. There is a model:

class Place(db.Model):
    # ...
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(16), nullable=False)
    sector_id = db.Column(db.Integer, nullable=False)
    col = db.Column(db.Integer, nullable=False)
    row = db.Column(db.Integer, nullable=False)
    place_type_id = db.Column(db.Integer, nullable=False)
    is_blocked_for_in = db.Column(db.Boolean, nullable=False)
    is_blocked_for_out = db.Column(db.Boolean, nullable=False)
    last_inventorization_at = db.Column(db.DateTime, nullable=True)
    # ...


I want to implement sending results to the front, taking into account the received filters. And if with filters for a complete match, everything is generally clear. Well, i.e. front makes a request .../places?col=2&row=3&place_type_id=1 , then you can process:

for arg in request.args:
    filters[arg] = request.args[arg]

places = Place.query.filter_by(**filters).all()


But with complex filters, you can’t do that anymore. For example, if you need to make a selection by the name field with like, a list comes to place_type_id, not an int value, last_inventorization_at is specified by an interval, and so on. How are these filters usually implemented? It is clear that you can hardcode with a bunch of ifs, but I want to make a beautiful solution.

I would be very grateful for an answer

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question