title: SQLAlchemy update if unique key exists
body: <p>I've got a class:</p>
  
  <pre><code>class Tag(Base, TimestampMixin):
      """Tags"""
      __tablename__ = 'tags'
      __table_args__ = {'mysql_engine' : 'InnoDB', 'mysql_charset' : 'utf8' }
  
      id = Column(Integer(11), autoincrement = True, primary_key = True)
      tag = Column(String(32), nullable = False, unique = True)
      cnt = Column(Integer(11), index = True, nullable = False, default = 1)
  
      def __init__(self, tag):
          t = session.query(Tag).filter_by(tag=tag).first()
          if t:
              self.cnt = t.cnt+1
              self.tag = t.tag
          else:
              self.tag = tag
  
      def __repr__(self):
          return "&lt;Tag('%s')&gt;" % (self.tag, )
  
      def __unicode__(self):
          return "%s" % (self.tag, )
  </code></pre>
  
  <p>When adding tag:</p>
  
  <pre><code>tag = Tag('tag')
  session.add(tag)
  session.commit()
  </code></pre>
  
  <p>I want it to update existing <code>tag</code>.</p>
  
  <p>Of course, I could've done this:</p>
  
  <pre><code>tag = session.query(Tag).filter_by(tag='tag').first()
  if tag:
      tag.cnt++
  else:
      tag = Tag('tag')
  session.add(tag)
  session.commit()
  </code></pre>
  
  <p>but, keeping such logic in <code>Tag</code> class seems to be more clear - possibly keeps me off of the shotgun surgery.</p>
  
  <p>How do I get there?
  I'm pretty new to <code>Python</code> and <code>SQLAlchemy</code>, so any additional thoughts on my code will be appreciated.</p>
  
  <p>Thank you.</p>
  
  <p>P.S. <code>SQLAlchemy</code> is SO GIGANTIC and they don't provide a handy way to do <code>INSERT ... ON DUPLICATE KEY UPDATE</code>, huh? WOW!</p>