Tengo una clase:actualización SQLAlchemy si existe clave única
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 "<Tag('%s')>" % (self.tag,)
def __unicode__(self):
return "%s" % (self.tag,)
Al añadir la etiqueta:
tag = Tag('tag')
session.add(tag)
session.commit()
lo quiero para actualizar tag
existente.
Por supuesto, podría haber hecho esto:
tag = session.query(Tag).filter_by(tag='tag').first()
if tag:
tag.cnt++
else:
tag = Tag('tag')
session.add(tag)
session.commit()
pero, manteniendo esa lógica en Tag
clase parece ser más claro - posiblemente me mantiene fuera de la cirugía de escopeta.
¿Cómo llegar? Soy bastante nuevo en Python
y SQLAlchemy
, por lo que cualquier idea adicional sobre mi código será apreciada.
Gracias.
P.S. SQLAlchemy
es TAN GIGANTE y no proporcionan una forma práctica de hacer INSERT ... ON DUPLICATE KEY UPDATE
, ¿eh? ¡GUAUU!
intento session.me rge (tag) en lugar de session.add (tag) –