Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django difference between clear() and delete()

Tags:

python

django

I'm using django for a while now and recently bumped into this :

user.groups.clear()

usually what I'd do is this:

user.groups.all().delete()

what's the difference?

like image 648
elad silver Avatar asked Mar 30 '15 11:03

elad silver


2 Answers

user.groups.all().delete() will delete the related group objects, while user.groups.clear() will only disassociate the relation:

https://docs.djangoproject.com/en/dev/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.

like image 139
Selcuk Avatar answered Oct 20 '22 04:10

Selcuk


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.

like image 40
Alasdair Avatar answered Oct 20 '22 03:10

Alasdair