Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

python - I wanna resist id in serial number

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' is not a valid UUID."]

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...