1

I have been working in Django for about a week now so I don't have much idea on the following. I need to create a sequence for a field in my model and postgres database that auto increments starting at 1000. So it would list like: 1000, 1001, 1002, etc....

From what I have researched so far I would need to extend the save function and check the previous value in the db.

The end result is to be able to post to an API using this model and this field increments like above.

class MyModel(AuditMixin, models.Model):
    order_number = models.IntegerField(blank=False)

    def get_number(self):
        return ???

    def save(self):
        ??? .save()
user2168066
  • 627
  • 11
  • 21
  • Sorry for the delay, I actually did something very similiar. I just made a manual migration with create sequence as you described. – user2168066 Jun 09 '17 at 00:11
  • Good to know, but may I suggest adding it to the migrations. So that the process is reproducible. Also your tests may not work. – e4c5 Jun 09 '17 at 00:31

1 Answers1

1

From what I have researched so far I would need to extend the save function and check the previous value in the db.

Generally doing a SELECT followed by an insert or update based on that SELECT is a bad idea for any RDBMS. Because this can lead to race conditions and databases have built in mechanisms that avoid this race condition and are usually faster.

Postgresql has a Serial type. It will be included in the django.contrib.posgres from the next major release of Django but for now. Create a custom migration like this:

CREATE SEQUENCE my_serial START 1000;
ALTER TABLE myapp_mymodel ALTER COLUMN order_number SET DEFAULT nextval('my_serial');

If you have never created a custom migration before, look up RunPython

e4c5
  • 52,766
  • 11
  • 101
  • 134