2

I would like to start my ids on a django model from 1000. I've found this response on Stackoverflow but I am missing something in my implementation because it is not working.

This is my code in apps.py

from django.apps import AppConfig
from django.db.models.signals import post_migrate
from django.db import IntegrityError

from invoice.models import Invoice

def my_callback(sender, **kwargs):
    if sender.name =="invoice":
        try:
            Invoice.objects.create(id=999)
            Invoice.objects.delete()
        except IntegrityError:
            pass

class InvoiceConfig(AppConfig):
    name = 'invoice'

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

I've then ensure migrate takes place but the model continues to increment from low numbers. What am I missing?

HenryM
  • 5,557
  • 7
  • 49
  • 105
  • Most databases each time when booting calculate the *maximum* id in the database and then increment from that part on. So in case you reboot the database, and no such invoice is present, it starts iterating from `0`. – Willem Van Onsem Jun 13 '18 at 13:34
  • It will work if you do not *reboot* the database server typically (since as long as the database is *active*, it stores the ID dispatcher in memory), but there are no guarantees how IDs are dispatched when a database reboots. Typically this should not be your problem either. If you really need something else, I propose to write an extra column, where you implement some sort of dispatcher yourself. – Willem Van Onsem Jun 13 '18 at 13:36
  • 1
    In short: this is something you typically can *not* control (in general). Specific databases like PostgreSQL however allow one to define a *sequence*, so then you have more control. – Willem Van Onsem Jun 13 '18 at 13:36

0 Answers0