Mam klasę:SQLAlchemy zmiana jeśli unikalny klucz istnieje
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,)
Dodając tag:
tag = Tag('tag')
session.add(tag)
session.commit()
chcę go zaktualizować istniejący tag
.
Oczywiście, mogłem zrobiłem to:
tag = session.query(Tag).filter_by(tag='tag').first()
if tag:
tag.cnt++
else:
tag = Tag('tag')
session.add(tag)
session.commit()
ale utrzymując taką logikę w Tag
klasy wydaje się być bardziej jasne - ewentualnie trzyma mnie z dala od zabiegu shotgun.
Jak się tam dostać? Jestem całkiem nowy dla Python
i SQLAlchemy
, więc wszelkie dodatkowe uwagi dotyczące mojego kodu zostaną docenione.
Dziękuję.
P.S. SQLAlchemy
jest TAK GIGANTYCZNY i nie zapewnia wygodnego sposobu na wykonanie INSERT ... ON DUPLICATE KEY UPDATE
, co? ŁAŁ!
try session.me rge (tag) zamiast session.add (tag) –