Python Sqlalchemy与内置类型的关系

Python Sqlalchemy与内置类型的关系,python,sqlalchemy,relationship,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__ = 'itemcomment

我有类似的想法:

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”)
或使用
直接迭代字符串注释,以在item.comments:
中添加注释。我假设它可以与@property一起工作,但是有没有一种方法可以设置关系以透明地处理它呢?

这正是扩展所做的。在您的情况下,这意味着拥有如下模型:

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
参数进行显式创建。

另外,您可能需要将
注释
重命名为
\u comments
comms
重命名为
注释

谢谢,这正是我要找的。我只需将
cascade=“all,delete orphan”
添加到关系中,即可删除注释。