简体   繁体   English

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

[英]How to remove all items from many-to-many collection in SqlAlchemy?

when I need to remove an object from declarative ORM many-to-many relationship, I am supposed to do this: 当我需要从声明性ORM多对多关系中删除一个对象时,我应该这样做:

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. 在那种情况下,请告诉我。

This is the standard Python idiom for clearing a list – assigning to the “entire list” slice: 这是用于清除列表的标准Python习惯用法 - 分配给“整个列表”切片:

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. SQLAlchemy的关系是检测属性 ,意味着它们保持列表(或集合,字典等)的接口,但任何更改都反映在数据库中。 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. 这意味着您可以使用关系对列表执行任何操作,而SQLA会透明地侦听更改并相应地更新数据库。

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. 似乎工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM