Django, access to the PostgreSQL sequence

In the Django application, I need to create an order number that looks like this: yyyymmddnnnn, in which yyyy = year, mm = month, dd = day and nnnn is a number from 1 to 9999.

I thought I could use the PostgreSQL sequence, since the generated numbers are atomic, so I can be sure when the process will get a number whose number is unique.

So, I created a PostgreSQL sequence:

CREATE SEQUENCE order_number_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9999
START 1
CACHE 1
CYCLE;

This sequence can be accessed as tables having one row. Therefore, in the checkout.py file, I created a Django model to access this sequence.

class OrderNumberSeq(models.Model):
    """
    This class maps to OrderNumberSeq which is a PostgreSQL sequence.
    This sequence runs from 1 to 9999 after which it restarts (cycles) at 1.
    A sequence is basically a special single row table.
    """
    sequence_name = models.CharField(max_length=128, primary_key=True)
    last_value = models.IntegerField()
    increment_by = models.IntegerField()
    max_value = models.IntegerField()
    min_value = models.IntegerField()
    cache_value = models.IntegerField()
    log_cnt = models.IntegerField()
    is_cycled = models.BooleanField()
    is_called = models.BooleanField()

    class Meta:
        db_table = u'order_number_seq'

I set sequence_name as the primary key since Django insists on having the primary key in the table.

I created a get_order_number.py file with the contents:

def get_new_order_number():
    order_number = OrderNumberSeq.objects.raw("select sequence_name, nextval('order_number_seq') from order_number_seq")[0]

    today = datetime.date.today()
    year = u'%4s' % today.year
    month = u'%02i' % today.month
    day = u'%02i' % today.day

    new_number = u'%04i' % order_number.nextval
    return year+month+day+new_number

, 'get_new_order_number()' django, , .

>>> checkout.order_number.get_new_order_number()
u'201007310047'
>>> checkout.order_number.get_new_order_number()
u'201007310048'
>>> checkout.order_number.get_new_order_number()
u'201007310049'

, . django, , .

:

import get_order_number

order_number = get_order_number.get_new_order_number()

. , , 2. , .

+3
1

, , : , . , : , , - .

, , , , , .

. - Neat Freak SQL Antipatterns. ( : , ).

+3

Source: https://habr.com/ru/post/1757498/


All Articles