tho*_*rha 4 python postgresql orm sqlalchemy
所以我对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')
Run Code Online (Sandbox Code Playgroud)
我不知道如何使用@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'
Run Code Online (Sandbox Code Playgroud)
小智 8
您可以使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3155 次 |
| 最近记录: |