在SqlAlchemy模型类定义中通过@property获取Python getter和setter:HOWTO
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在SqlAlchemy模型类定义中通过@property获取Python getter和setter:HOWTO,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2533字,纯文字阅读大概需要4分钟。
内容图文
所以我对sqlalchemy和ORM很新.我有一个现有的数据库,postgresql,我已经创建了一个模型来与数据库进行通信.下面是我的Transcribers表的类.通过它查询时,所有这些都有效.我只是在课堂上设置getter和setter时遇到问题.
class Transcriber(Base):
__tablename__ = 'transcribers'
__table_args__ = (
UniqueConstraint('projectid', 'email'),
)
transcriberid = Column(Integer, primary_key=True, server_default=text("nextval('transcribers_transcriberid_seq'::regclass)"))
projectid = Column(ForeignKey(u'projects.projectid', ondelete=u'CASCADE'), index=True)
email = Column(Text, nullable=False)
created = Column(DateTime, nullable=False, server_default=text("now()"))
onwebsite = Column(Boolean, nullable=False, server_default=text("true"))
def __repr__(self):
return "<Transcriber(transcriberid:'%s', projectID:'%s', email:'%s', created:'%s', onwebsite:'%s'" %(self.transcriberid, self.projectid, self.email, self.created, self.onwebsite)
@property
def transcriberid(self):
return self.transcriberid
def email(self):
return self.email
@email.setter
def email(self, value):
self.email = value
project = relationship(u'Project')
我不知道如何使用@property方法访问对象中的不同变量.我想使用这种方法,因为我相信它更加pythonic.
那么现在我如何实际调用这些方法.他们是否正确设置.
我在启动Class时收到此错误
Traceback (most recent call last):
File "./test.py", line 4, in <module>
from peraAPI import DBSession, getProjectbyId, getTransById
File "/Users/tcrha/bin/working/PeraPera/peraAPI/__init__.py", line 7, in <module>
from model_local import Project, Transcriber
File "/Users/tcrha/bin/working/PeraPera/peraAPI/model_local.py", line 110, in <module>
class Transcriber(Base):
File "/Users/tcrha/bin/working/PeraPera/peraAPI/model_local.py", line 133, in Transcriber
@email.setter
AttributeError: 'function' object has no attribute 'setter'
解决方法:
你可以使用hybrid_property.
在这种情况下,代码的简化版本应如下所示:
from sqlalchemy.ext.hybrid import hybrid_property
class Transcriber(Base):
__tablename__ = 'transcribers'
__table_args__ = (
UniqueConstraint('projectid', 'email'),
)
transcriberid = Column(Integer, primary_key=True, server_default=text("nextval('transcribers_transcriberid_seq'::regclass)"))
projectid = Column(ForeignKey(u'projects.projectid', ondelete=u'CASCADE'), index=True)
created = Column(DateTime, nullable=False, server_default=text("now()"))
onwebsite = Column(Boolean, nullable=False, server_default=text("true"))
_email = Column('email', Text, nullable=False)
@hybrid_property
def email(self):
return self._email
@email.setter
def email(self, email):
self._email = email
内容总结
以上是互联网集市为您收集整理的在SqlAlchemy模型类定义中通过@property获取Python getter和setter:HOWTO全部内容,希望文章能够帮你解决在SqlAlchemy模型类定义中通过@property获取Python getter和setter:HOWTO所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。