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)