擅长:python、mysql、java
<p>试试这个:</p>
<pre><code>post = db.session.query(Post).get(1)
post.tags = []
db.session.commit()
</code></pre>
<p>在这里,我们将集合<code>post.tags</code>重新定义为空数组并提交更改。为了解释这一点,我将参考<a href="http://docs.sqlalchemy.org/en/rel_0_9/orm/collections.html#custom-collection-implementations">SQLAlchemy docs</a>:</p>
<blockquote>
<p>Collections in SQLAlchemy are transparently instrumented. Instrumentation means that normal operations on the collection are tracked and result in changes being written to the database at flush time. </p>
</blockquote>
<p>因此,SQLAlchemy会跟踪我们对集合post.tags所做的更改,并在提交时对其进行更新。</p>
<p>如果我们只有一个标记(比如<code>sometag</code>),我们可以使用<code>remove</code>方法,如下所示:</p>
<pre><code>post = db.session.query(Post).get(1)
post.tags.remove(sometag)
db.session.commit()
</code></pre>