Y
Y
Yourmind2021-12-02 03:48:58
Python
Yourmind, 2021-12-02 03:48:58

How to form a query using sqlalchemy?

I have a table

class Order(Base):
    __tablename__ = "orders"

    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    uuid = sqlalchemy.Column(UUID(as_uuid=True), default=uuid.uuid4, unique=True)
    type = sqlalchemy.Column(sqlalchemy.String)
    status = sqlalchemy.Column(sqlalchemy.String)
    cluster_uuid = sqlalchemy.Column(UUID(as_uuid=False))
    params = sqlalchemy.Column(sqlalchemy_jsonfield.JSONField(enforce_string=False, enforce_unicode=False), default="{}")


Also, what I use to make queries
db = SessionLocal()

I get some dictionary (d1) with field values ​​and some dictionary (d2) with field values ​​in the params field
How to write a universal search query for these values. For example:
d1 = {'status': 'ready', 'cluster_uuid': 'xxx'}
d2 = {"first_atr': 'my_atr', "second_atr': 'my_atr1', }
Here you need to find all orders in the 'ready' status ' and the cluster 'xxx' and whose params field contains json, the first_atr field is equal to my_atr and the second_atr field is equal to my_atr1.

I do not know in advance what will come in these dictionaries. How to write so that the search is one query?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nvlveu, 2021-12-02
@nvlveu

model.query.filter_by(**params).first()
Where model is the model you will search in and params is your dictionary

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question