title: SQLAlchemy check before insert in Python
body: <p>I have a question about a more proper/efficient way how to check if a entry is already in a database table.</p>
  
  <p>Suppose that I have a table called <code>Foo</code> with single attribute and <code>Name</code> which is also <strong><em>unique</em></strong>.</p>
  
  <p>What is a better way to check before insert if there is already an entry with such name? I can think of two alternatives:</p>
  
  <pre><code>from sqlalchemy import MetaData, Table, Column, String, \
  create_engine
  from sqlalchemy.orm import mapper, relationship, sessionmaker
  from sqlalchemy.ext.declarative import declarative_base
  from sqlalchemy.exc import IntegrityError
  
  Base = declarative_base()
  
  class Foo(Base):
      __tablename__ = "foo"
  
      name = Column(String(), primary_key=True)
  
      @staticmethod
      def silent_insert1(name):
              if not session.query(Foo).filter(Foo.name == name).first():
                      foo = Foo()
                      foo.name = name
                      session.add(foo)
                      session.commit()
              else:
                      print("already exists 1")
  
      @staticmethod
      def silent_insert2(name):
              try:
                      foo = Foo()
                      foo.name = name
                      session.add(foo)
                      session.commit()
              except(IntegrityError):
                      print("already exists 2")
  
  
  engine = create_engine('sqlite://', echo=True)
  Base.metadata.create_all(engine)
  session = sessionmaker(engine)()
  
  Foo.silent_insert1(1)
  Foo.silent_insert2(1)
  </code></pre>
  
  <p>In the first <strong>silent_insert1</strong>, there is of course a race condition. The second seems more bullet proof. </p>
  
  <p>Which one is better? Is even a better way or recommended way how to check this?</p>
  
  <p>Thank you</p>