user442920
user442920

Reputation: 847

Basequery object returned instead of model object from sqlalchemy query.filter

I have two lines in my flask code that are making dbase calls. This line:

articles += Entries.query.filter(and_(Entries.id == article.article_id, Entries.tags.like(search_string))) # @UndefinedVariable

returns a Models.Entries object.

Whereas this line :

articles.append(Entries.query.filter(Entries.id == 3)) # @UndefinedVariable

returns a Basequery object. I need a Models.Entries object! What might be going on?

Upvotes: 2

Views: 1789

Answers (1)

davidism
davidism

Reputation: 127200

Assuming articles is a list, adding to a list is basically equivalent to articles.extend(other_iterable). A Query is iterable: iterating it, returning results.

In the second example, you are not executing the query, you are appending it to the list. The equivalent code to += would use extend, not append:

articles.extend(Entries.query.filter_by(id=3))

It looks like you're querying single items by id. Rather than performing multiple queries and collecting the results, perform one query over a list of ids and get the results directly.

articles = Entries.query.filter(Entries.id.in_([1, 2, 3, 4])).all()

Upvotes: 3

Related Questions