142π
In Django
1 : Django model class has default field with name id
which is auto increment Field.
2 : You can define your own auto increment field using AutoField
field.
class Order(models.Model): auto_increment_id = models.AutoField(primary_key=True) # primary_key = True if you do not want to use default field "id" given by django to your model
db design
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ | core_order | CREATE TABLE `core_order` ( `auto_increment_id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`auto_increment_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.01 sec)
If you want to use djangoβs default id as increment field .
class Order(models.Model): add_date = models.DateTimeField(auto_now_add=True)
db design
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+ | core_order | CREATE TABLE `core_order` ( `id` int(11) NOT NULL AUTO_INCREMENT, `add_date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
24π
In django with every model you will get the by default id field that is auto increament. But still if you manually want to use auto increment. You just need to specify in your Model AutoField
.
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
you can read more about the auto field in django in Django Documentation for AutoField
- [Django]-How to resize an ImageField image before saving it in python Django model
- [Django]-Django edit user profile
- [Django]-How do I use pagination with Django class based generic ListViews?
8π
You can create an autofield. Here is the documentation for the same
Please remember Django wonβt allow to have more than one AutoField in a model, In your model you already have one for your primary key (which is default). So youβll have to override modelβs save method and will probably fetch the last inserted record from the table and accordingly increment the counter and add the new record.
Please make that code thread safe because in case of multiple requests you might end up trying to insert same value for different new records.
- [Django]-How to change empty_label for modelForm choice field?
- [Django]-Class has no objects member
- [Django]-How to get the current language in Django?
8π
class Belly(models.Model):
belly_id = models.AutoField(primary_key=True)
belly_name = models.CharField(max_length=50)
******** or *******
class Belly(models.Model):
belly_name = models.CharField(max_length=50)
The difference is:
The first table has the primary key belly_id
(specified as AutoField
) and second table has the primary key id
(implicitly).
I think no need to use this directly; a primary key field will automatically be added to your model if you donβt specify. Otherwise
Check the Django Documentation for AutoField for further details related to AutoField
.
- [Django]-How to expire session due to inactivity in Django?
- [Django]-How to concatenate strings in django templates?
- [Django]-Naming convention for Django URL, templates, models and views
7π
Edited: Fixed mistake in code that stopped it working if there were no
YourModel
entries in the db.
Thereβs a lot of mention of how you should use an AutoField, and of course, where possible you should use that.
However there are legitimate reasons for implementing auto-incrementing fields yourself (such as if you need an id to start from 500 or increment by tens for whatever reason).
In your models.py
from django.db import models
def from_500():
'''
Returns the next default value for the `ones` field,
starts from 500
'''
# Retrieve a list of `YourModel` instances, sort them by
# the `ones` field and get the largest entry
largest = YourModel.objects.all().order_by('ones').last()
if not largest:
# largest is `None` if `YourModel` has no instances
# in which case we return the start value of 500
return 500
# If an instance of `YourModel` is returned, we get it's
# `ones` attribute and increment it by 1
return largest.ones + 1
def add_ten():
''' Returns the next default value for the `tens` field'''
# Retrieve a list of `YourModel` instances, sort them by
# the `tens` field and get the largest entry
largest = YourModel.objects.all().order_by('tens').last()
if not largest:
# largest is `None` if `YourModel` has no instances
# in which case we return the start value of 10
return 10
# If an instance of `YourModel` is returned, we get it's
# `tens` attribute and increment it by 10
return largest.tens + 10
class YourModel(model.Model):
ones = models.IntegerField(primary_key=True,
default=from_500)
tens = models.IntegerField(default=add_ten)
- [Django]-How do I reuse HTML snippets in a django view
- [Django]-What's the best way to store a phone number in Django models?
- [Django]-Separating form input and model validation in Django?
2π
You can override Django save method official doc about it.
The modified version of your code:
class Order(models.Model):
cart = models.ForeignKey(Cart)
add_date = models.DateTimeField(auto_now_add=True)
order_number = models.IntegerField(default=0) # changed here
enable = models.BooleanField(default=True)
def save(self, *args, **kwargs):
self.order_number = self.order_number + 1
super().save(*args, **kwargs) # Call the "real" save() method.
Another way is to use signals. More one:
- [Django]-Many-To-Many Fields View on Django Admin
- [Django]-Django staticfiles not found on Heroku (with whitenoise)
- [Django]-Django.db.migrations.exceptions.InconsistentMigrationHistory
1π
What I needed: A document number with a fixed number of integers that would also act like an AutoField
.
My searches took me all over incl. this page.
Finally I did something like this:
I created a table with a DocuNumber
field as an IntegerField with foll. attributes:
max_length=6
primary_key=True
unique=True
default=100000
The max_length
value anything as required (and thus the corresponding default=
value).
A warning is issued while creating the said model, which I could ignore.
Afterwards, created a document (dummy) whence as expected, the document had an integer field value of 100000.
Afterwards changed the model key field as:
- Changed the field type as:
AutoField
- Got rid of the
max_length
Anddefault
attributes - Retained the
primary_key = True
attribute
The next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.
So far so good.
- [Django]-Feedback on using Google App Engine?
- [Django]-How to serve media files on Django production environment?
- [Django]-In Django β Model Inheritance β Does it allow you to override a parent model's attribute?
1π
If you are not going to use the auto increment field as the primary key, you can define an integer field and update this integer field in the save() method.
class Order(models.Model):
cart = models.ForeignKey(Cart)
add_date = models.DateTimeField(auto_now_add=True)
order_number = models.IntegerField()
enable = models.BooleanField(default=True)
def save(self, *args, **kwargs):
orders = Order.objects.all()
if orders.exists() and self._state.adding:
last_order = orders.latest('order')
self.order = int(last_order.order) + 1
super().save(*args, **kwargs)
If we do not use self._state.adding here, the order will increase automatically in the update process as well. We only query the self._state.adding that we want to increase the order in the create process.
- [Django]-How to set up a PostgreSQL database in Django
- [Django]-Using JSON in django template
- [Django]-How does Django's nested Meta class work?
0π
You can use default primary key (id) which auto increaments.
Note: When you use first design i.e. use default field (id) as a primary key, initialize object by mentioning column names.
e.g.
class User(models.Model):
user_name = models.CharField(max_length = 100)
then initialize,
user = User(user_name="XYZ")
if you initialize in following way,
user = User("XYZ")
then python will try to set id = βXYZβ which will give you error on data type.
- [Django]-How do you catch this exception?
- [Django]-Django β Website Home Page
- [Django]-Homepage login form Django