Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom id field in Django model

Tags:

python

django

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.

like image 679
user2719152 Avatar asked Jan 31 '16 03:01

user2719152


People also ask

Does Django create ID field?

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.

Does Django automatically create ID?

Django will create or use an autoincrement column named id by default, which is the same as your legacy column.

How do I add a field to a Django model?

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.


1 Answers

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.

like image 150
eugene Avatar answered Oct 13 '22 17:10

eugene