SQLALchemy: update with in clause from kwargs

MRAB python at mrabarnett.plus.com
Tue Aug 3 22:19:30 EDT 2021


On 2021-08-04 02:08, Larry Martell wrote:
> I am trying to write a function that takes kwargs as a param and
> generates an update statement where the rows to be updated are
> specified in an in clause.
> 
> Something like this:
> 
>      def update_by_in(self, **kwargs):
>          filter_group = []
>          for col in kwargs['query_params']:
>              # obviously this line does not work as col is a string,
> but this is the intent
>              filter_group.append(col.in_(tuple(kwargs['query_params'][col])))
> 
>          self._session.query(self.model_class).filter(*filter_group).update(kwargs['values'])
> 
> self.update_by_in(
>      **{'query_params': {'companyCode': ['A', 'B', 'C']},
>          'values': {'portfolioName': 'test'}}
>   )
> 
> Is there a way to do this? I think I need to use setattr in building
> up the filter_group list, but I'm not quite sure how to do it.
> 
If it's any help, on this page:

     https://docs.sqlalchemy.org/en/14/core/metadata.html

it has this:

     # access the column "employee_id":
     employees.columns.employee_id

     # or just
     employees.c.employee_id

     # via string
     employees.c['employee_id']


More information about the Python-list mailing list