我想拒绝序列号中的ID [英] I wanna resist id in serial number

查看:57
本文介绍了我想拒绝序列号中的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拒绝序列号为1,2,3 ・ ・ ・的id.我写了一些代码来拒绝用户数据,如

I wanna resist id in serial number like 1,2,3・・・.I wrote codes to resist User data like,

from django.db import models
import uuid

# Create your models here.
def get_next():
    try:
        return Users.objects.latest('pk').increment_num + 1
    except:
        return 1

class Users(models.Model):
    id = models.UUIDField(primary_key=True, default=get_next, editable=False)
    sex = models.CharField(max_length=100, null=True, default=None)
    age = models.CharField(max_length=100, null=True, default=None)

但是当我尝试拒绝用户的数据时,

But when I try to resist user's data,

django.core.exceptions.ValidationError:['1'不是有效的UUID."]

django.core.exceptions.ValidationError: ["'1' is not a valid UUID."]

发生错误.因此,我重写了 id = models.IntegerField(primary_key = True,default = get_next),但是如果我拒绝多个用户的数据,则仅保留id = 1的数据,我无法理解,但删除了其他数据.我的代码有什么问题?我该如何解决?

error happens. So I rewrote id = models.IntegerField(primary_key=True, default=get_next), but if I resist multiple user's data, only id=1's data is remain and I cannot understand but other data was deleted. What is wrong in my code? How should I fix this?

推荐答案

UUID不是数字,但是您可以简单地生成新的UUID

UUID is not a number but you can generate a new UUID simple

import uuid
from django.db import models

# Create your models here.
def get_next():
    return uuid.uuid4()

class Users(models.Model):
    id = models.UUIDField(primary_key=True, default=get_next, editable=False)
    sex = models.CharField(max_length=100, null=True, default=None)
    age = models.CharField(max_length=100, null=True, default=None)

默认情况下,Django将存储整数主键.为此,您需要删除一些代码.

By default Django will store Integer Primary keys. In order to do that you need to remove some of your code.

from django.db import models


class Users(models.Model):
    sex = models.CharField(max_length=100, null=True, default=None)
    age = models.CharField(max_length=100, null=True, default=None)

在数据库后端等待,它将是连续的.

Pending on you database backend it will be sequential.

这篇关于我想拒绝序列号中的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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