在SQLAlchemy中以多对多关系插入数据

bod*_*ydo 17 sqlalchemy

假设我有3个班的SQLAlchemy: ,Topic,.TagTag_To_Topic

有可能写出类似的东西:

new_topic = Topic("new topic")
Topics.tags = ['tag1', 'tag2', 'tag3']
Run Code Online (Sandbox Code Playgroud)

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

到目前为止,由于多对多的关系,我无法弄清楚如何做到这一点.(如果它是一对多的,那将非常容易,SQLAlchemy默认情况下会这样做.但这是多对多的.)

这可能吗?

谢谢,Boda Cydo.

van*_*van 17

通过使用association_proxy可以简化多对多关系.

然后,我会保留关系,以免干扰SA的作用:

# here *tag_to_topic* is the relation Table object
Topic.tags = relation('Tag', secondary=tag_to_topic)
Run Code Online (Sandbox Code Playgroud)

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

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")
Run Code Online (Sandbox Code Playgroud)

然后这段代码应该工作:

# Test
o = Topic()
session.add(o)
session.commit()
o.str_tags = ['tag1']
o.str_tags = ['tag1', 'tag4']
session.commit()
Run Code Online (Sandbox Code Playgroud)