How to Create an Auto Incrementing Integer Field

5,163 views
Skip to first unread message

Cody Scott

unread,
Jul 19, 2013, 3:00:17 PM7/19/13
to django...@googlegroups.com

I have a list of articles and you can control the order of the articles by changing the order field in the model


order = models.IntegerField(default=1)


I would like it to default to one more than the last article or one more than the largest order (since you can set the order)


I can't use AutoField because it is only for primary keys.

Rafael E. Ferrero

unread,
Jul 22, 2013, 8:25:10 AM7/22/13
to django...@googlegroups.com
Maybe extending save() method ?
Somethin like...

class your_model(models.Model):
    order = models.IntegerField(default=1)

    def save(self, *args, **kwargs):
        if not self.id:
            #here must to find the last order then sum one and save the result
            self.order=result
        super(your_model, self).save(*args,**kwargs)
       

I'm not quite sure, but i think that this is the way.




2013/7/19 Cody Scott <cody.j....@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
Rafael E. Ferrero
Claro: (03562) 15514856

Christian Erhardt

unread,
Jul 22, 2013, 9:48:51 AM7/22/13
to django...@googlegroups.com
 
They determine the next value by calling a function called number(). In your case it would look something like this:

class Cliente(models.Model):
    """This is the client data model, it holds all client information. This
       docstring has to be improved."""
    def number():
        no = Cliente.objects.all().aggregate(Max(order))
        if no == None:
            return 1
        else:
            return no + 1

    clientcode = models.IntegerField(_('Code'), max_length=6, unique=True, \
    default=number)
 

Cody Scott

unread,
Jul 22, 2013, 4:35:23 PM7/22/13
to django...@googlegroups.com
Thank you very much, that was exactly what I was looking for.

Christian Erhardt

unread,
Jul 23, 2013, 7:50:49 AM7/23/13
to django...@googlegroups.com
you are very welcome

Gabriel - Iulian Dumbrava

unread,
Jul 27, 2013, 3:37:24 AM7/27/13
to django...@googlegroups.com
I ended up using a stored procedure for something similar, triggered on after insert.
Reply all
Reply to author
Forward
0 new messages