Deleting records
To delete a single model instance, you can use the Model.delete_instance()
shortcut. delete_instance()
will delete the given model instance and can optionally delete any dependent objects recursively (by specifying recursive=True).
>>> user = User.get(User.id == 1)
>>> user.delete_instance() # Returns the number of rows deleted.
1
>>> User.get(User.id == 1)
UserDoesNotExist: instance matching query does not exist:
SQL: SELECT t1."id", t1."username" FROM "user" AS t1 WHERE t1."id" = ?
PARAMS: [1]
To delete an arbitrary set of rows, you can issue a DELETE query. The following will delete all Tweet
objects that are over one year old:
>>> query = Tweet.delete().where(Tweet.creation_date < one_year_ago)
>>> query.execute() # Returns the number of rows deleted.
7
For more information, see the documentation on:
Model.delete_instance()
Model.delete()
DeleteQuery