Skip to content

Commit 858bb12

Browse files
eikichi18Photonios
authored andcommitted
Support of restart_identity on truncate operation
1 parent 422e91f commit 858bb12

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

docs/source/deletion.rst

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,28 @@ By default, Postgres will raise an error if any other table is referencing one o
4848
MyModel.objects.truncate(cascade=True)
4949
print(MyModel1.objects.count()) # zero records left
5050
print(MyModel2.objects.count()) # zero records left
51+
52+
53+
Restart identity
54+
****************
55+
56+
If specified, any sequences on the table will be restarted.
57+
58+
.. code-block:: python
59+
60+
from django.db import models
61+
from psqlextra.models import PostgresModel
62+
63+
class MyModel(PostgresModel):
64+
pass
65+
66+
mymodel = MyModel.objects.create()
67+
assert mymodel.id == 1
68+
69+
MyModel.objects.truncate(restart_identity=True) # table is empty after this
70+
print(MyModel.objects.count()) # zero records left
71+
72+
# Create a new row, it should get ID 1 again because
73+
# the sequence got restarted.
74+
mymodel = MyModel.objects.create()
75+
assert mymodel.id == 1

psqlextra/manager/manager.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ def __init__(self, *args, **kwargs):
3737
)
3838

3939
def truncate(
40-
self, cascade: bool = False, using: Optional[str] = None
40+
self,
41+
cascade: bool = False,
42+
restart_identity: bool = False,
43+
using: Optional[str] = None,
4144
) -> None:
4245
"""Truncates this model/table using the TRUNCATE statement.
4346
@@ -51,14 +54,19 @@ def truncate(
5154
False, an error will be raised if there
5255
are rows in other tables referencing
5356
the rows you're trying to delete.
57+
restart_identity:
58+
Automatically restart sequences owned by
59+
columns of the truncated table(s).
5460
"""
5561

5662
connection = connections[using or "default"]
5763
table_name = connection.ops.quote_name(self.model._meta.db_table)
5864

5965
with connection.cursor() as cursor:
60-
sql = "TRUNCATE TABLE %s" % table_name
66+
sql = f"TRUNCATE TABLE {table_name}"
6167
if cascade:
6268
sql += " CASCADE"
69+
if restart_identity:
70+
sql += " RESTART IDENTITY"
6371

6472
cursor.execute(sql)

0 commit comments

Comments
 (0)