Login

Reset Postgres Sequences On Every Migrate

Author:
stuartaccent
Posted:
December 30, 2017
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

If you create alot of data via fixtures or by inserting the pk you will more than likely see alot of issues with the sequences being out in postgres when creating new records.

Similar to: Foo with the pk(x) already exists

This you have to fix by updating the postgres sequences to start at the correct number.

The below will ensure after every migrate all sequences in predefined apps get reset.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
####################################################
# Create an app config, example: `myapp/apps.py`

import re
from io import StringIO

from django.apps import AppConfig
from django.core.management import call_command
from django.db import connection
from django.db.models.signals import post_migrate


def reset_sequences(sender, **kwargs):
    """ reset the sql sequences """
    print('reset_sequences')

    # list of apps to reset 
    app_names = []

    for app_name in app_names:
        output = StringIO()
        call_command('sqlsequencereset', app_name, stdout=output)
        sql = output.getvalue()

        # Remove terminal color codes from sqlsequencereset output
        ansi_escape = re.compile(r'\x1b[^m]*m')
        sql = ansi_escape.sub('', sql)

        with connection.cursor() as cursor:
            cursor.execute(sql)


class MyAppConfig(AppConfig):
    name = 'myapp'

    def ready(self):
        post_migrate.connect(reset_sequences, sender=self)

####################################################
# Make sure there is a `myapp/models.py` in the
# same app with at least the following 

from django.db import models

####################################################
# Add the config to your `INSTALLED_APPS`

INSTALLED_APPS = [
    ...
    'myapp.apps.MyAppConfig',
    ...
]

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.