以下完全不完整的代码段使用声明性语法定义了基本的SQLAlchemy关系...
Base = declarative_base()
class Movie(Base):
__tablename__ = 'movies'
id = Column(Integer, primary_key=True)
name = Column(String)
director = relationship("People", uselist = False)
class People(Base):
__tablename__ = 'people'
id = Column(Integer, primary_key=True)
name = Column(String, nullable = false)
要访问导演名称,它将类似于:
assert isinstance(movie, Movie) # <-- retrieved with query or whatever
director_name = movie.director.name
如果为方便起见,我总是希望director
关系只给我导演的名字而不是人物实例,你是怎么做到的?例如:它应该像这样工作:
assert isinstance(movie, Movie)
director_name = movie.director # <-- should get the string directly
我99%肯定我以前做过这个,但是找不到任何参考代码或文档了。我试图找到它有点疯狂。 Stack Overflow将是答案的良好/永久参考位置。
答案 0 :(得分:2)
关联代理用于Python端的各种“对象引用 - >属性引用”转换样式。文档已经过新更新和重写:
http://www.sqlalchemy.org/docs/orm/extensions/associationproxy.html
答案 1 :(得分:2)
如果您使用财产怎么办?
class Movie(Base):
__tablename__ = 'movies'
id = Column(Integer, primary_key=True)
name = Column(String)
_director = relationship("People", uselist = False)
@property
def director_name(self):
return self._director.name