I'm using django for a while now and recently bumped into this :
我现在正在使用django一段时间,最近碰到了这个:
user.groups.clear()
usually what I'd do is this:
通常我会做的是:
user.groups.all().delete()
what's the difference?
有什么不同?
2 个解决方案
#1
10
user.groups.all().delete()
will delete the related group objects, while user.groups.clear()
will only disassociate the relation:
user.groups.all()。delete()将删除相关的组对象,而user.groups.clear()只会取消关联:
https://docs.djangoproject.com/en/1.7/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear
Removes all objects from the related object set: Note this doesn’t delete the related objects – it just disassociates them.
从相关对象集中删除所有对象:请注意,这不会删除相关对象 - 它只是将它们取消关联。
Note that deleting the related objects may have the side effect that other users belonging to the same group may also be deleted (by cascade), depending on the ForeignKey rules specified by on_delete
.
请注意,删除相关对象可能会产生副作用,即属于同一组的其他用户也可能会被删除(通过级联),具体取决于on_delete指定的ForeignKey规则。
#2
4
user.groups.clear()
This unlinks the groups from the user, but does not affect the groups themselves.
这会取消组与用户的链接,但不会影响组本身。
user.groups.all().delete()
This deletes the actual groups. You probably don't want to do this because there might be other users that belong to those groups as well.
这会删除实际的组。您可能不希望这样做,因为可能还有其他用户属于这些组。
#1
10
user.groups.all().delete()
will delete the related group objects, while user.groups.clear()
will only disassociate the relation:
user.groups.all()。delete()将删除相关的组对象,而user.groups.clear()只会取消关联:
https://docs.djangoproject.com/en/1.7/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear
Removes all objects from the related object set: Note this doesn’t delete the related objects – it just disassociates them.
从相关对象集中删除所有对象:请注意,这不会删除相关对象 - 它只是将它们取消关联。
Note that deleting the related objects may have the side effect that other users belonging to the same group may also be deleted (by cascade), depending on the ForeignKey rules specified by on_delete
.
请注意,删除相关对象可能会产生副作用,即属于同一组的其他用户也可能会被删除(通过级联),具体取决于on_delete指定的ForeignKey规则。
#2
4
user.groups.clear()
This unlinks the groups from the user, but does not affect the groups themselves.
这会取消组与用户的链接,但不会影响组本身。
user.groups.all().delete()
This deletes the actual groups. You probably don't want to do this because there might be other users that belong to those groups as well.
这会删除实际的组。您可能不希望这样做,因为可能还有其他用户属于这些组。