python - Sqlalchemy 与内置类型的关系

标签 python sqlalchemy relationship

我有类似的东西:

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>

最佳答案

到底是什么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

关于python - Sqlalchemy 与内置类型的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21164673/

相关文章:

python - 使用 SQLAlchemy ORM 基于多对一关系中的一个对象过滤查询

sqlalchemy 按日期列仅选择 x newset 天

python - 在 Django 中处理 M2M 关系

php - 保存与 Yii 有多对多关系的模型

mysql - 将数据库关系更改为 Laravel eloquent

python - 如何制作一个 Python 程序来演示 Zipf 定律?

Python 多处理 : Sending data to a process

python - SQLAlchemy:没有名为 'mysql' 的模块

python - SQLAlchemy - 模型 - 使用动态字段 - ActiveRecord

python - Python 如何只读取文件的一部分