如何从 SqlAlchemy 中的多对多集合中删除所有项目?

发布于 2024-12-11 23:03:58 字数 294 浏览 4 评论 0原文

当我需要从声明性 ORM 多对多关系中删除一个对象时,我应该这样做:

blogpost.tags.remove(tag)

嗯。如果我需要清除所有这些关系(不仅仅是一种),我该怎么办?典型情况:我想为我的博客文章设置一个新的标签列表。所以我需要...:

  1. 删除该博客文章和标签之间的所有现有关系
  2. 设置新关系并创建新标签(如果不存在)。

当然,可能有更好的方法来做到这一点。在这种情况下,请告诉我。

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...:

  1. Remove all existing relations between that blogpost and tags.
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笔芯 2024-12-18 23:03:58

这是清除列表的标准 Python 习惯用法 - 分配给“整个列表”切片:

blogpost.tags[:] = []

您可能希望直接分配新的标签集,而不是空列表。

blogpost.tags[:] = new_tags

SQLAlchemy 的关系是检测属性,这意味着它们保留列表(或集合、字典等)的接口,但任何更改都会反映在数据库中。这意味着您可以对列表执行的任何操作都可以通过关系执行,而 SQLA 会透明地侦听更改并相应地更新数据库。

This is the standard Python idiom for clearing a list – assigning to the “entire list” slice:

blogpost.tags[:] = []

Instead of the empty list, you may want assign the new set of tags directly.

blogpost.tags[:] = new_tags

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.

等风也等你 2024-12-18 23:03:58

确认两位炼金术士所报告的内容。

blogpost.tags[:] = new_tags

会抱怨

TypeError: 'AppenderBaseQuery' object does not support item assignment

blogpost.tags = new_tags

似乎工作正常。

Confrimed for what Two-Bit Alchemist has reported.

blogpost.tags[:] = new_tags

will complain about

TypeError: 'AppenderBaseQuery' object does not support item assignment

But

blogpost.tags = new_tags

seems to work fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文