Skip to content Skip to sidebar Skip to footer

Auto Increment Non-pk Field Starting At 1000

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 i

Solution 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 START1000;
ALTERTABLE myapp_mymodel ALTERCOLUMN order_number SETDEFAULT nextval('my_serial');

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

Post a Comment for "Auto Increment Non-pk Field Starting At 1000"