1👍
No, That is not the correct way of making a primary key in Django, in fact you don’t have to specify a Primary key for your model, because django will automatically add a field to hold the primary key for you.
In your settings.py file, you will find a line with:
DEFAULT_AUTO_FIELD = ‘django.db.models.BigAutoField’
which will automatically creates an ‘id’ field in all of your models by default. The BigAutoField is a 64bit integer that automatically increments according to available ids from 1 to 9223372036854775807.
class Profile(models.Model):
customer_username = models.CharField(max_length=100)
customer_email = models.EmailField()
the Profile model will have three fields: id, customer_username, customer_email
but, in case you want to overide the primary key, let’s say for instane by using UUIDs instead of regular ids, you can overide it as follows:
import uuid
class Profile(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4,editable=False)
customer_username = models.CharField(max_length=100)
customer_email = models.EmailField()
for more details, please refer to the django documentation: https://docs.djangoproject.com/en/4.0/ref/models/fields/#primary-key
6👍
The correct syntax for primary key is-:
class profiles(models.model):
customer_ID = models.IntegerField(primary_key=True)
- [Django]-Best Practice to get related values in django without DoesNotExist error
- [Django]-Django workflow to convert model superclass to subclass
- [Django]-Double Foreign Key in Django?
- [Django]-Getting first image from html using Python/Django
- [Django]-Django: Force cache-refresh after update
2👍
Is this the correct way of making a primary key in django??
No. You use an AutoField
[Django-doc] for a primary key, since then the values are dispatched by the database, so:
class profiles(models.model):
customer_ID = models.AutoField(primary_key=True, editable=False)
But you do not have to specify a primary key: if you do not specify one yourself, Django will add one with the name id
to the model automatically.
- [Django]-Django deep serialization – follow reverse foreign key constraints
- [Django]-How to use a different database for Heroku review apps?
- [Django]-AttributeError: 'SigSafeLogger' object has no attribute 'logger'
- [Django]-Getting Illegal instruction: illegal hardware instruction python manage.py runserver on Apple M1 chip