How to Make an Auto Increment Integer Field in Django

create auto increment integer field in django

You did not specify a field with primary_key=True [Django-doc], this means that Django will automatically add a field to your model named id.

If you do not change the DEFAULT_AUTO_FIELD setting [Django-doc], or set the default_auto_field attribute [Django-doc] of the AppConfig of your app, it will use an AutoField [Django-doc] which is an IntegerField that will automatically add a value. You thus can access this with myuser.id or myuser.pk.

Please do not use loops to filter on the username, this will result in linear search in the Django/Python layer. It is better to filter the database with:

from django.shortcuts import get_object_or_404

def profile(request, username):
user = get_object_or_404(User_account, username=username)
return render(request, 'account_app/profile.html', context={'user_info': user})

How to make an IntegerField/CharField be auto-incrementing field in Django as 1000001, 1000002

Solution is make your field as Auto-field. If you make it auto-field then django won't add primary key which cause error

can't have more than one AutoField.
You need to explicitly specify the primary key as

field = models.AutoField(primary_key=True) # or False

To start counting from 1000001 best way is to modify migration file. It depends in the database you are using. If you using Postgres then it looks like this. Edit operations in migration or run the SQL command DB command prompt:

operations = [
migrations.CreateModel(...),
# mysql specific
migrations.RunSQL('alter table tablename auto_increment=1000001'),
]

The alter command will change depends on the database you are using.

If you want a custom AutoField then you can create a char field and make editable false. Then specify value manually. Refer: https://techstream.org/Web-Development/Custom-Auto-Increment-Field-Django

Auto Increment Non-primary Key Field in Abstract Base Class in Django

Since I was mainly interested in this value in the Django Admin, I went with this method in the ModelAdmin, using the information from this question and answer:

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):

def increment_order(self):
obj = MyModel.objects.order_by('-order').first()
number = obj.order
return number + 1 if number else 0

def get_changeform_initial_data(self, request):
return {'order': self.increment_order}

The provided answer was helpful but had a few things incorrect about it, which is why I'm not selecting it as accepted. Thanks either way @weAreStarDust.

Auto increment a value in Django with respect to the previous one

Django won't let you have more than one AutoField in a model, and you already have one for your primary key. So you'll have to override save and will probably need to look back at the table to figure out what to increment.

Something like this:

class Product(models.Model): 
code = models.IntegerField()
number = models.IntegerField()
...

def get_serial_number(self):
"Get formatted value of serial number"
return "%.2d-%.3d" % (self.code, self.product)

def save(self):
"Get last value of Code and Number from database, and increment before save"
top = Product.objects.order_by('-code','-number')[0]
self.code = top.code + 1
self.number = top.number + 1
super(Product, self).save()

# etc.

Note that without some kind of locking in your save method, you can run into a concurrency problem (two threads trying to store the same values in code and number).



Related Topics



Leave a reply



Submit