假设我使用关联表在多对多关系中有一个文章模型和一个Tag模型 . 标签具有属性id(主键)和tag_name . 文章有很多标签 .
我想创建一个带有标签的新文章,并且我要添加现有标签的ID .
我有这样的事情:
self.tags = [ Tag.query.filter_by(id=tag_id).first() for tag_id in tag_ids ]
(我使用的是Flask-SQLAlchemy . )
如何在不必要地查询Tag对象的情况下执行此操作?
我想实际上只是在关联表中插入tag_id,article_id关联;我可以不使用原始声明吗?
1 回答
如果你直接映射了关联表,比如
TagAssociation
,那么你可以创建TagAssociation(article_id=x, tag_id=y)
. 如果OTOH表只出现在relationship()
的secondary
参数中,则ORM不需要运行insert()
,尽管您使用Session.execute()
,即Session.execute(assoc_table.insert(), params={"article_id": x, "tag_id": y})
.