Generate a random alphanumeric string as a primary key for a model

前端 未结 3 1939
Happy的楠姐
Happy的楠姐 2021-02-03 12:28

I would like a model to generate automatically a random alphanumeric string as its primary key when I create a new instance of it.

example:

from django.d         


        
3条回答
  •  死守一世寂寞
    2021-02-03 13:01

    Try this:

    The if statement below is to make sure that the model is update able.

    Without the if statement you'll update the id field everytime you resave the model, hence creating a new model everytime

    from uuid import uuid4
    from django.db import IntegrityError
    
    class Book(models.Model):
        id = models.CharField(primary_key=True, max_length=32)
    
        def save(self, *args, **kwargs):
            if self.id:
                super(Book, self).save(*args, **kwargs)
                return
    
            unique = False
            while not unique:
                try:
                    self.id = uuid4().hex
                    super(Book, self).save(*args, **kwargs)
                except IntegrityError:
                    self.id = uuid4().hex
                else:
                    unique = True
    

提交回复
热议问题