I am making a web application in Django. I want to use custom id field in my model and i know about uuid module. The problem is i don't know where to put this logic. I don't want to use Django's AutoField. I want it to be such that if one row is entered then this id field must be custom not AutoField. A silly idea comes to my mind is to change the id field later after row insertion with my custom id. Can anyone help me to sort this problem out. Any assistance is highly appreciated.
Primary KeysBy default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field.
Django will create or use an autoincrement column named id by default, which is the same as your legacy column.
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB. Save this answer.
https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields
If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.
So you want (from https://docs.djangoproject.com/en/dev/ref/models/fields/#uuidfield)
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# other fields
you don't have to name the field id
I think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With