如何从 SqlAlchemy 中的多对多集合中删除所有项目?
当我需要从声明性 ORM 多对多关系中删除一个对象时,我应该这样做:
blogpost.tags.remove(tag)
嗯。如果我需要清除所有这些关系(不仅仅是一种),我该怎么办?典型情况:我想为我的博客文章设置一个新的标签列表。所以我需要...:
- 删除该博客文章和标签之间的所有现有关系。
- 设置新关系并创建新标签(如果不存在)。
当然,可能有更好的方法来做到这一点。在这种情况下,请告诉我。
when I need to remove an object from declarative ORM many-to-many relationship, I am supposed to do this:
blogpost.tags.remove(tag)
Well. What am I supposed to do if I need to purge all these relations (not only one)? Typical situation: I'd like to set a new list of tags to my blogpost. So I need to...:
- Remove all existing relations between that blogpost and tags.
- Set new relations and create new tags if they don't exist.
Of course, there could be a better way of doing this. In that case please let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是清除列表的标准 Python 习惯用法 - 分配给“整个列表”切片:
您可能希望直接分配新的标签集,而不是空列表。
SQLAlchemy 的关系是检测属性,这意味着它们保留列表(或集合、字典等)的接口,但任何更改都会反映在数据库中。这意味着您可以对列表执行的任何操作都可以通过关系执行,而 SQLA 会透明地侦听更改并相应地更新数据库。
This is the standard Python idiom for clearing a list – assigning to the “entire list” slice:
Instead of the empty list, you may want assign the new set of tags directly.
SQLAlchemy's relations are instrumented attributes, meaning that they keep the interface of a list (or set, dict, etc), but any changes are reflected in the database. This means that anything you can do with a list is possible with a relation, while SQLA transparently listens to the changes and updates the database accordingly.
确认两位炼金术士所报告的内容。
会抱怨
但
似乎工作正常。
Confrimed for what Two-Bit Alchemist has reported.
will complain about
But
seems to work fine.