Django difference between clear () and delete ()

I have been using django for a while and have recently come across this:

user.groups.clear() 

usually what i would do is:

 user.groups.all().delete() 

who cares?

+6
source share
2 answers

user.groups.all().delete() will delete the associated group objects, and user.groups.clear() will disconnect the relation:

https://docs.djangoproject.com/en/1.7/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear

Deletes all objects from the corresponding set of objects: Note that this does not delete related objects - it just parses them.

Please note that deleting related objects can have a side effect, which can be deleted by other users belonging to the same group (in cascade), depending on the ForeignKey rules specified by on_delete .

+9
source
 user.groups.clear() 

This will remove the groups from the user, but does not affect the groups themselves.

 user.groups.all().delete() 

This removes the actual groups. You probably do not want to do this, because there may be other users belonging to these groups.

+4
source

Source: https://habr.com/ru/post/984429/


All Articles