2012-09-20

If a record exists

A common action when synchronizing data between some source and a database is to check if such-and-such record already exists and needs to be updated or if a new record needs to be created.  The SQLAlchemy's one() method [of the query object] provides an easy way to check to see if such-and-such record exists;  but it doesn't return either an ORM object or None - if no record is found it raises an exception.  This is surprising at first as x=do;if-not-x is possibly the most common of all Python constructs.  The corresponding SQLAlchemy construct is just to catch the NoResultFound exception.

from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound

try:
    db.query( VendorCross ).\
        filter( and_( VendorCross.vendor_code == vendor_code,
                      VendorCross.oem_code = oem_code,
                      VendorCross.oem_partcode = oem_partcode ).one( )
except NoResultFound:
    # no such record exists
else:
    # record exists


No comments:

Post a Comment