Q1980
Q1980

Reputation: 47

Why are they using .first here?

In my class they used the following code:

pet = session.query(Pet).filter_by(name="Marshmallow").first()

What does the .first() do here?

Upvotes: 1

Views: 63

Answers (1)

P3qiUB
P3qiUB

Reputation: 156

.first() returns the first object matched by the query, or None if there was no match. Without .first(), session.query(Pet).filter_by(name="Marshmallow") returns an instance of Query, not the object.

See the official SQLAlchemy document Query.first().

Upvotes: 5

Related Questions