0

I am creating a search bar where users can enter keywords such as movie title, imdb id, year of release to find a list of matching movies. I have a tabel called Movie looks something like this:

id  title   year    runtime rating
tt1490017   The Lego Movie  2014    100 7.8
tt0111161   The Shawshank Redemption    1994    142 9.3
tt0068646   The Godfather   1972    175 9.2

I have a query that looks for movies containing the keyword(s) entered by the user that looks like this:

movies = db.session.query(Movie).filter_by(or_(id=searchkey,title=searchkey,year=searchkey))

where searchkey is whatever is entered by the user in the search bar. However when I run this, it gives me the error saying that TypeError: or_() got an unexpected keyword argument 'id'. Did I mess up my syntax or is there something else wrong? Would really appreciate your help.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
oceandye
  • 309
  • 3
  • 6
  • 14
  • 1
    According to, e.g., [this](https://stackoverflow.com/questions/7942547/using-or-in-sqlalchemy) you want to write something like `or_(Movie.id == searchkey, Movie.title == searchkey, Movie.year == searchkey)`. `or_` takes conditions as positional parameters it takes no keyword parameters – Giacomo Alzetta Jun 28 '19 at 07:59
  • @GiacomoAlzetta Thanks for the response but in that example, `filter()` was used and for filter(), for every conditional Movie.x, there must be `filter(or_(Movie.x == y, Movie.x == z))` . It doesn't work if its `filter(or_(Movie.x == y, Movie.a == b))` . – oceandye Jun 28 '19 at 08:08
  • I don't think you can do this using `filter_by`. `filter_by` is a convenience method to be used when you have a simple filter on **one** field. See [this other](https://stackoverflow.com/questions/2128505/whats-the-difference-between-filter-and-filter-by-in-sqlalchemy) question that shows that you should use `filter` to use `or_`. – Giacomo Alzetta Jun 28 '19 at 09:12
  • I see, Thanks for the help, I'll try and figure out what I did wrong then since it still doesn't work. – oceandye Jun 29 '19 at 01:49

0 Answers0