【问题标题】:Inserting data in Many to Many relationship in SQLAlchemy在 SQLAlchemy 中以多对多关系插入数据
【发布时间】:2012-03-04 16:32:34
【问题描述】:

假设我在 SQLALchemy 中有 3 个类:TopicTagTag_To_Topic

是否可以这样写:

new_topic = Topic("new topic")
Topics.tags = ['tag1', 'tag2', 'tag3']

我想在Tag表中自动插入'tag1','tag2'和'tag3',并在Tag_To_Topic表中插入new_topic和这3个标签之间的正确关系。

到目前为止,由于多对多关系,我无法弄清楚如何做到这一点。 (如果是一对多,那就很容易了,SQLAlchemy已经默认做到了。但这是多对多。)

这可能吗?

谢谢,博达·赛多。

【问题讨论】:

    标签: sqlalchemy


    【解决方案1】:

    首先你可以使用association_proxy 来简化你的多对多关系。

    然后,我将保持关系不变,以免干扰 SA 的工作:

    # here *tag_to_topic* is the relation Table object
    Topic.tags = relation('Tag', secondary=tag_to_topic)
    

    我建议您只创建一个简单的包装器属性,将字符串列表转换为关系对象(您可能会重命名关系)。您的标签类看起来类似于:

    class Topic(Base):
        __tablename__ = 'topic'
        id = Column(Integer, primary_key=True)
        # ... other properties
    
        def _find_or_create_tag(self, tag):
            q = Tag.query.filter_by(name=tag)
            t = q.first()
            if not(t):
                t = Tag(tag)
            return t
    
        def _get_tags(self):
            return [x.name for x in self.tags]
    
        def _set_tags(self, value):
            # clear the list first
            while self.tags:
                del self.tags[0]
            # add new tags
            for tag in value:
                self.tags.append(self._find_or_create_tag(tag))
    
        str_tags = property(_get_tags,
                            _set_tags,
                            "Property str_tags is a simple wrapper for tags relation")
    

    那么这段代码应该可以工作:

    # Test
    o = Topic()
    session.add(o)
    session.commit()
    o.str_tags = ['tag1']
    o.str_tags = ['tag1', 'tag4']
    session.commit()
    

    【讨论】:

    • 我想对你帮助我深表感谢,Van。您关于使用关联代理并通过添加辅助方法改进类的建议产生了很好的代码和解决方案。谢谢!
    • 谢谢,范。但是如何“选择”标签,例如,获取所有标签为“news”和 o.year > 2010 的主题(只是 Topic() 实例中的任意属性)?
    猜你喜欢
    • 2020-03-23
    • 2016-04-04
    • 2019-04-10
    • 1970-01-01
    • 2015-03-29
    • 2021-06-03
    • 2013-08-18
    • 2013-06-04
    • 2014-10-29
    相关资源
    最近更新 更多