Django模型中的自定义ID字段 [英] Custom id field in Django model
问题描述
https://docs.djangoproject.com/en/1.9/topics/db/models/#automatic-primary-key-fields
如果要指定自定义主键,只需在其中一个字段上指定
primary_key = True即可。如果Django看到你有
明确设置Field.primary_key,它将不会添加自动ID
列。
所以你想要(从 https: //docs.djangoproject.com/es/1.9/ref/models/fields/#django.db.models.UUIDField )
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key = True,default = uuid .uuid4,editable = False)
#其他字段
你不必命名我认为这个字段 id
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.
https://docs.djangoproject.com/en/1.9/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/es/1.9/ref/models/fields/#django.db.models.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.
这篇关于Django模型中的自定义ID字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!