sqlalchemy - How to use descriptors in sqlachemy.orm.synonym -
i have code working fine:
def get_timestamp(ts): return datetime.utcfromtimestamp(ts) def set_timestamp(dt): return time.mktime(dt.timetuple()) class group(base): __tablename__ = 'group' _created = column('created', integer, nullable=false) @property def created(self): return get_timestamp(self._created) @created.setter def created(self, value): self._created = set_timestamp(value)
i want code this, it's not working:
created = synonym('_created', descriptor=property(get_timestamp, set_created))
because passed in self
1st param.
i'd use get_timestamp
, set_timestamp
across project of cause. i'm not going make them methods of class stand alone function.
how can achieve this?
edit: take option2, , still open other answers.
option-1: code below should work (you not need have class in order define self
):
def pget_timestamp(self): return datetime.utcfromtimestamp(self._created) def pset_timestamp(self, dt): self._created = time.mktime(dt.timetuple()) class group(base): __tablename__ = 'group' id = column(integer, primary_key=true) _created = column('created', integer, nullable=false) created = synonym(_created, descriptor=property(pget_timestamp, pset_timestamp), )
option-2: if need same on many classes, leverage mixins
from sqlalchemy.ext.declarative import declared_attr class _createdmixin(object): _created = column('created', integer, nullable=false) def pget_timestamp(self): return datetime.utcfromtimestamp(self._created) def pset_timestamp(self, dt): self._created = time.mktime(dt.timetuple()) @declared_attr def created(cls): return synonym('_created', descriptor=property(cls.pget_timestamp, cls.pset_timestamp), ) class group(_createdmixin, base): # @note: adding *_createdmixin* bases defines both column , synonym __tablename__ = 'group' id = column(integer, primary_key=true)
alternatively, if all classes, make _createdmixin
base class models:
base = declarative_base(engine, cls=_createdmixin) class group(base): __tablename__ = 'group' id = column(integer, primary_key=true)
option-3: of above using hybrid attributes
note: make set/get functions in-sync: either both or none use utc-enabled functionality. (unless in utc-0) setting 1 value created
not return same 1 back.
Comments
Post a Comment