[Fixed]-Django difference between clear() and delete()

22👍

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.

👤Selcuk

7👍

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.

Leave a comment