我有类似的东西:
class Item(Base, DBBase):
__tablename__ = 'item'
id = Column(Integer, primary_key = True)
name = Column(String), nullable = True)
comments = relationship('ItemComment')
class ItemComment(Base, DBBase):
__tablename__ = 'itemcomments'
item_id = Column(Integer, ForeignKey('item.id'), nullable = False, primary_key=True)
comment = Column(String), nullable = False, primary_key=True)
我想知道是否可以将关系映射直接映射到字符串,这样我就可以避免直接在代码中处理ItemComment对象。例如,添加这样的新注释:item.comments.append("hello")
或使用for comment in item.comments:
直接遍历字符串注释。我认为它可以与@property一起使用,但有没有办法设置关系以透明地处理它?</ p>
答案 0 :(得分:2)
Association Proxy
扩展正在做什么。在你的情况下,它意味着拥有如下模型:
class Item(Base, DBBase):
__tablename__ = 'item'
id = Column(Integer, primary_key = True)
name = Column(String, nullable = True)
comments = relationship('ItemComment')
comms = association_proxy('comments', 'comment',
creator=lambda comment: ItemComment(comment=comment),
)
class ItemComment(Base, DBBase):
__tablename__ = 'itemcomments'
item_id = Column(Integer, ForeignKey('item.id'), nullable = False, primary_key=True)
comment = Column(String, nullable = False, primary_key=True)
def __init__(self, comment):
self.comment = comment
您可以完全按照自己的意愿使用它:
my_item.comms.append("super")
print "All Comments: ", my_item.comms
另外一条评论:您需要指定creator
参数(如上面的代码中所示),否则您需要ItemComment
上有一个参数构造函数(如上所述),但其中一个就足够了。我通常喜欢通过creator
参数进行显式创建
此外,您可能希望将comments
重命名为_comments
,将comms
重命名为comments
。