我有一个模型 Foo。这与 Moo 有着多对多的关系。
现在 Foo 在其多对多字段中有许多对象,即它有 moo1、moo2、moo3 等,如何一起删除所有对象?我知道我们可以单独删除每个。
foo = FOO()
foo.save()
foo.moo.add(moo1)
foo.moo.remove(moo1)
Run Code Online (Sandbox Code Playgroud)
IE
foo = FOO()
foo.save()
foo.moo.add(moo1)
foo.moo.add(moo2)
foo.moo.reset() # This should remove all objects that have been added
# in this field. This does not work but I want
# something like this.
Run Code Online (Sandbox Code Playgroud)
使用该clear方法。
\n\n\n从相关对象集中删除所有对象:
\n
b = Blog.objects.get(id=1)\nb.entry_set.clear() \nRun Code Online (Sandbox Code Playgroud)\n\n\n\n请注意,这不会\xe2\x80\x99 删除相关对象\xe2\x80\x93,它只是取消它们的关联。
\n\n就像remove() 一样,clear() 仅适用于\n null=True 的ForeignKeys。
\n
| 归档时间: |
|
| 查看次数: |
2216 次 |
| 最近记录: |