user1896796
user1896796

Reputation: 749

Adding multiple conditions in where clause in bulk update in sqlalchemy

Below code for bulk update is working where benefits_dict is my list of dictionaries.

conn.execute(MedicalPlanBenefit.__table__.update()
                             .where(MedicalPlanBenefit.__table__.c.user_id == bindparam('user_id')),
                             benefits_dict)

Now when I go and add multiple conditions to my where clause like below, it doesn't work.

conn.execute(MedicalPlanBenefit.__table__.update()
                             .where(MedicalPlanBenefit.__table__.c.user_id == bindparam('user_id') & MedicalPlanBenefit.__table__.c.test_id == bindparam('test_id')),
                             benefits_dict)

How do you add multiple conditions in this case?

My benefits_dict:

{'user_id': 1, 'email_address' : '[email protected]', 'id':12, 'test_id': 31},
   {'user_id': 1, 'email_address' : '[email protected]', 'id':13, 'test_id': 31},
   {'user_id': 2, 'email_address' : '[email protected]', 'id':14, 'test_id': 31},
   {'user_id': 2, 'email_address' : '[email protected]', 'id':15, 'test_id': 31} 

Upvotes: 1

Views: 2855

Answers (1)

benvc
benvc

Reputation: 15120

You can either chain where clauses together or use the and_ operator to add multiple conditions to your where clause (be sure to import the and_ operator from sqlalchemy.sql). See Conjunctions in the SQLAlchemy Expression Language Tutorial. For example:

# Using and_ operator
where(
    and_(
        table.c.id == 'id',
        table.c.name == 'name'
        )
    )

# chaining where clauses
where(table.c.id == 'id').\
where(table.c.name == 'name')

Upvotes: 4

Related Questions