Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: Check if object is already present in table

I have a class Item whose id is a primary key and auto-generated. Now I read data from some other external source, create an Item object, and need to check if this object is already present in my items table. How do I do it?

like image 725
missingfaktor Avatar asked Oct 05 '12 15:10

missingfaktor


2 Answers

The most efficient way is to use exists()

q = session.query(Item.id).filter(Item.email==email)
session.query(q.exists()).scalar()    # returns True or False
like image 79
Salami Avatar answered Oct 03 '22 06:10

Salami


You could query for items that have the same attributes and check if the count is greater than zero.

if session.query(Item.id).filter(Item.email==newItem.email,
                                 Item.type==newItem.type).count() > 0:
    // item exists
like image 31
Nathan Villaescusa Avatar answered Oct 03 '22 06:10

Nathan Villaescusa