sqlmodel icon indicating copy to clipboard operation
sqlmodel copied to clipboard

How to use the "IN" clause using the select statement

Open Praveenstein opened this issue 3 years ago • 4 comments

First Check

  • [X] I added a very descriptive title to this issue.
  • [X] I used the GitHub search to find a similar issue and didn't find it.
  • [X] I searched the SQLModel documentation, with the integrated search.
  • [X] I already searched in Google "How to X in SQLModel" and didn't find any information.
  • [X] I already read and followed all the tutorial in the docs and didn't find an answer.
  • [X] I already checked if it is not related to SQLModel but to Pydantic.
  • [X] I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • [ ] I commit to help with one of those options 👆

Example Code

# Something similar to this from sqlalchemy

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

Description

Trying to use the "IN" clause in the sqlmodel, where I could filter out based on a list of values

Operating System

Linux

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.10.4

Additional Context

No response

Praveenstein avatar May 30 '22 09:05 Praveenstein

Hi, try this way:

        db_setting = session.exec(select(Settings).where(Settings.id.in_([1,2,3]))).all()

mgurg avatar May 31 '22 05:05 mgurg

Thanks, @mgurg, this works. Weirdly enough, pylance won't recognize .in_() as a member function of the attribute, so I was thinking this wouldn't work. Any idea why?

higorc-turing avatar Jun 01 '22 22:06 higorc-turing

try https://sqlmodel.tiangolo.com/tutorial/where/#type-annotations-and-errors

from sqlmodel import col
col(Settings.id).in_([1,2,3])

hrehfeld avatar Jun 03 '22 15:06 hrehfeld

I read the whole documentation and don't know how I could have missed this. Thank you, @hrehfeld!

higorc-turing avatar Jun 28 '22 18:06 higorc-turing