How to Create an Auto Increment in Django that is not pk

Asked

Viewed 1,344 times

2

I’m creating a memo system with Django and it’s working fine, but I need to put in a self-improvement field that’s not pk. I have this field in my models.

Memo = models.IntegerField()

I need it already receive the value or the id or a counter, I am using python3 and Django 11.

If anyone can give me a light thank you!

  • Transferring the id value to a document field is a bad idea, because that way you will be exposing the bank’s hold unnecessarily.

2 answers

3

You can use the Django-Sequence-field. Take an example from him:

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 by hand yourself too:

def next_sequence():
    _model = Memorando.objects.filter().order_by('-Memo')[:1]
    if _model.count() > 0:
        return int(_model[0].Memo) + 1
    return 0
  • Okay Dude, your answer is good, the first part uses a non-native Django package that just encapsulates, in a package, the function suggested in the second part that is copied from my edited reply. Stop denying my answers, man, what’s in it for you?

  • Once an answer has a "solution" that doesn’t work, and only at the end of the answer does one propose something that is not an answer (such as an auto increment using uuid), I negative. I win nothing, I lose 1 point. The community wins.

  • Strange isn’t it? doesn’t work but the answer was accepted. I think you rushed to criticize before analyzing. The community would gain more with common sense.

  • The answer being accepted is one thing, being right according to the question is something else. Hugs!

  • Man... unleash! get off my back.

  • 1

    Hello William IA! Guy also analyzed your response and used the alternative you proposed me face worked perfectly, thank you even for your help now I have via broad view of how to assemble the code here.

Show 1 more comment

-1


Edited
It seems that the original solution does not work, Django (v. 1.11) requires an autofield field to have the parameter primary_key=True, an error, 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 put in the file itself models or in another 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 on, the answer "original".

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 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

Only... if you haven’t defined a PK of your own autofield, when you try to spin the migrations to add your field to the bank, you will receive the msg:

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

Solution

Define your own PK on a field that is not autofield

Suggestion

If you don’t have a field that can guarantee it unique to use as PK make the PKas being uuid thus:

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  • following the Sidon tip I did import uuid and added the two lines,id = models.Uuidfield(primary_key=True, default=uuid.uuid4, Editable=False) Memo = models.AutoField(primary_key=False) e agora ele me rotorna o seguinte erro quando tento o migrate ou makemigrations, SystemCheckError: System check identified some issues:
ERRORS:
geral.Memo.Memo: (fields.E100) AutoFields must set primary_key=True.

  • @MARCELOPEREIRADASILVA, OK, I edited the answer, see if the new solution meets.

  • @MARCELOPEREIRADASILVA you tried the function after editing? It worked?

  • hi Sidon yesterday I had not as appeared some scolds here at work to solve I’m doing now, using the code you added

  • Sidon guy Thank you so much for your help! you not only showed me the way to solve my problem but also put arrows all over it your answer was "ball show" or better "data show" rsrsrs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.