Attributeerror- Sqlalchemy Flask

Asked

Viewed 118 times

0

'str' Object has no attribute 'contains'

I am trying to create a query using Flask-Sqlalchemy

Flask should return me a list of books according to the user’s search. It selects 4 search options and type in an input to search.

EX: It selects TITLE search and type "Lord" as input.

The query should return all books containing the word Lord in the TITLE.

I have 2 variables

info_type = request.form.get('book_tags')
book_info = request.form.get('search_value').lower()

And the query

Book.query.filter(Book.info_type.contains(book_info).all()

If I replace the variable "info_type" directly with ISBN, TITLE, AUTHOR, YEAR (possible values for the variable info_type) function namespace.

ex:

Book.query.filter(Book.author.contains(book_info).all()

But I need a variable, because there are 4 different types of research.

Can someone give me some idea how to fix this?

  • Try with like to see if it works.

1 answer

0


I was able to understand your problem - you need to practice a little with the language, and understand the difference of strings, variables and attributes -

It’s not because the attribute name you need is inside the variable info_type, that this name will automatically turn the attribute when you use it Book.info_type.

There are even programming languages in which this is impossible - only with a sequence of ifs same - ,

In Python there is yes, how to use the string that is inside the info_type variable to indent the attribute of the same name in the object Book - you have to use the function getattr.

In short, what you need specifically to pass this step is:

Book.query.filter(getattr(Book, info_type).contains(book_info).all()

But I would really recommend a lot, but quite practical in interactive language mode to understand the difference between typing an attribute name directly into the code, and having that name within a variable, among other things.

  • Thank you so much for your help! I’ve been trying to solve this for about 5 days. I’m learning this framework now, I’m going deeper! Thanks again!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.