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?
Asked
Active
Viewed 2.4k times
18

missingfaktor
- 90,905
- 62
- 285
- 365
-
1Is it a ``get_or_create`` scenario? If so: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create – Demian Brecht Oct 05 '12 at 15:07
-
@DemianBrecht, thanks for the response, but no, it isn't. – missingfaktor Oct 05 '12 at 15:09
-
@missingfaktor how do you know if it already exists? Based on the primary key? Or some other unique key? – jadkik94 Oct 05 '12 at 16:08
-
@jadkik94, a set of unique attributes. – missingfaktor Oct 05 '12 at 16:09
3 Answers
13
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

Nathan Villaescusa
- 17,331
- 4
- 53
- 56
-
1The `>0` is redundant since count() returns zero if no matches are found and a positive integer otherwise. – kalu Mar 17 '14 at 14:43
-
9@kalu: "Explicit is better than implicit." -- The Zen of Python – Brendon Crawford Apr 30 '14 at 00:17
-
3Using count makes the database do more work then it needs to. See my answer below for an efficient method. – Salami May 15 '16 at 11:56
3
You could try something similar to this:
from sqlalchemy import exc
try:
session.add(item)
session.commit()
except exc.IntegrityError:
session.rollback()
print 'This item fails one of the unique/foreign key checks!'
except:
print 'There was another error'
raise
else:
print 'Everything is OK'
This has the problem that it acts upon committing, and then rolls back...
Another option, if you can check the properties individually, then this might work:
session.query(Item).filter_by(x=item.x, y=item.y).count() == 0

jadkik94
- 7,000
- 2
- 30
- 39