Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SQLAlchemy's `one_or_none` query method?

I'm trying to use the one_or_none query method to retrieve a record from my database but when I pass in a kwargs like I normally would with the filter_by method, it says it doesn't expect that keyword.

I tried going through the doc, but there's not description of the method's argument or an example.

like image 780
proton Avatar asked Jan 23 '26 14:01

proton


1 Answers

If you do Product.query.filter_by(id=101).first(), and there is no product with id 101 in your database, it will return None. If you have a product with id 101 on your db, it will return the first database hit as an instance of class Product.

You can also do a Product.query.filter_by(name='apple').one_or_none(), which will return None if there is no product named apple in your database, or an instance of class Product if there is exactly one product named apple in your database, or raises an exception if there are multiple products named apple in your database.

like image 60
Joost Avatar answered Jan 26 '26 09:01

Joost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!