Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.db import models

class MyTemporaryObject(models.Model):
    id = AutoGenStringField(lenght=16, primary_key=True)
    some_filed = ...
    some_other_field = ...

in my mind the key should look something like this "Ay3kJaBdGfcadZdao03293". It's for very temporary use. In case of collision I would like it Django to try a new key.

I was wondering if there was already something out there, or a very simple solution I am not seeing (I am fairly new to python and Django). Otherwise I was thinking to do my own version of models.AutoField, would that be the right approach?

I have already found how to generate the key here, so it's not about the string generation. I would just like to have it work seamlessly with a simple Django service without adding too much complexity to the code.

EDIT: Possible solution? What do you think?

id = models.CharField(unique=True, primary_key=True, default=StringKeyGenerator(), editable=False)

with

class StringKeyGenerator(object):
    def __init__(self, len=16):
        self.lenght = len
    def __call__(self):
        return ''.join(random.choice(string.letters + string.digits) for x in range(self.lenght))

I came up with it after going through the Django documentation one more time.

like image 975
le-doude Avatar asked Dec 05 '13 05:12

le-doude


People also ask

How do you generate random alphanumeric strings?

Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.

How do you generate random alphanumeric strings in C++?

Example 1: Using the rand() Function to Generate Random Alphabets in C++ The following C++ program generates a random string alphabet by using rand() function and srand() function. The rand() function generates the random alphabets in a string and srand() function is used to seed the rand() function.

How do you generate a unique random alphanumeric string in Java?

Using randomUUID() util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.


2 Answers

One of the simplest way to generate unique strings in python is to use uuid module. If you want to get alphanumeric output, you can simply use base64 encoding as well:

import uuid
import base64
uuid = base64.b64encode(uuid.uuid4().bytes).replace('=', '')
# sample value: 1Ctu77qhTaSSh5soJBJifg

You can then put this code in the model's save method or define a custom model field using it.

like image 168
Amir Ali Akbari Avatar answered Sep 21 '22 14:09

Amir Ali Akbari


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
like image 29
Angky William Avatar answered Sep 21 '22 14:09

Angky William