Django模型中的自定义ID字段 [英] Custom id field in Django model

查看:1552
本文介绍了Django模型中的自定义ID字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django制作一个Web应用程序。我想在我的模型中使用自定义id字段,我知道uuid模块。问题是我不知道把这个逻辑放在哪里。我不想使用Django的AutoField。我想要这样,如果输入一行,那么这个id字段必须不是AutoField。我想到的一个愚蠢的想法是,在使用我的自定义ID插入行后,更改id字段。任何人都可以帮我解决这个问题。任何帮助都非常感激。

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆