How to Create an Auto Increment in Django other than pk

2

I am creating a memo system with django and it is working fine, but I need to put a self-increment field other than pk. I have this field in my models.

Memo = models.IntegerField()

I need it to already receive the value of either the id or a counter, I'm using python3 and django 11.

If someone can give me a light, I thank you!

    
asked by anonymous 16.08.2017 / 14:38

2 answers

-1
  

Edited
  It seems that the original solution does not work, django (v 1.11) requires that an autofield field has the primary_key=True parameter, an incor- nance, in my view, for what is the parameter? The way is to try to remedy with a function, see if it works, the function can be placed in the models file itself or in a separate file (as long as you import it in models.py )

import datetime
def increment_chamado():
    ultimo = Chamado.objects.all().order_by('id').last()
    if not ultimo:
        return str(datetime.date.today().year) + str(datetime.date.today().month).zfill(2) + '0000'
    ultimo_id = ultimo.chamado_id
    ultimo_int = int(ultimo_id[9:13])
    new_int = ultimo_int+1
    new_id = str(str(datetime.date.today().year)) + str(datetime.date.today().month).zfill(2) + str(new_int).zfill(4)
  return new_id

In models the field that identifies the call would be:

classe Chamado(models.Model):
    chamado_id = models.CharField(max_length = 20, default = 
        increment_chamado, editable=False)

Based on a post from thecstream.org.

  

From this point forward, the "original" answer.

AutoField

Integer field with automatic increment, Primary keys use it automatically. A primary key is automatically added to your template if you do not specify it.

If you add it to your template:

incremento = models.AutoField(primary_key=False)

You will be adding a field of the type you want (auto-increment) to your model.

SQN

If you have not defined a PK by itself, other than autofield , when you try to run migrations to add your field to the database, you will receive the msg:

AssertionError: A model can't have more than one AutoField.

Solution

Set your own PK over a field that is not autofield

Suggestion

If you do not have a field that can guarantee that it is unique to use as PK make PK to be uuid like this:

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
16.08.2017 / 16:44
3

You can use django-sequence-field . Here's an example:

from sequence_field.fields import SequenceField

# Create your models here.

class TestModel(models.Model):

    sequence = SequenceField(
        key='test.sequence.1',
        template='%Y%m%d%(code)s%NNNNN',
        params={'code':'ABC'},
        auto=True
    )

Testing the Model

from my_app.models import TestModel

obj = TestModel()
obj.save()

print obj.sequence # 20140703ABC00001

obj = TestModel()
obj.save()

print obj.sequence # 20140703ABC00002

Alternative

You can do this validation on the same hand too:

def next_sequence():
    _model = Memorando.objects.filter().order_by('-Memo')[:1]
    if _model.count() > 0:
        return int(_model[0].Memo) + 1
    return 0
    
16.08.2017 / 23:41