Custom id field in Django model


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.


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

So you want (from

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.

Answered By – eugene

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published