Ho una classe:aggiornamento SQLAlchemy se chiave univoca esiste
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,)
Quando si aggiungono tag:
tag = Tag('tag')
session.add(tag)
session.commit()
voglio aggiornare tag
esistente.
Certo, avrei potuto fare questo:
tag = session.query(Tag).filter_by(tag='tag').first()
if tag:
tag.cnt++
else:
tag = Tag('tag')
session.add(tag)
session.commit()
ma, mantenendo tale logica in Tag
classe sembra essere più chiaro - forse mi tiene fuori della chirurgia fucile.
Come arrivo? Sono abbastanza nuovo a Python
e SQLAlchemy
, quindi qualsiasi pensiero aggiuntivo sul mio codice sarà apprezzato.
Grazie.
P.S. SQLAlchemy
è così GIGANTIC e non forniscono un modo pratico per fare INSERT ... ON DUPLICATE KEY UPDATE
, eh? WOW!
prova session.me rge (tag) invece di session.add (tag) –