[Fixed]-How to set a random integer as the default value for a Django CharField?

32👍

This way you generate a random number once. You need to define a function such as:

def random_string():
    return str(random.randint(10000, 99999))

And then define your model as you already have, without () in order to pass a reference to the function itself rather a value returned by the function:

class Content(models.Model):
    ......
    unique_url = models.CharField(default = random_string)
👤Wtower

5👍

You can generate a random string by passing the function as the default value. The function will run and set the default value with the return value of the function. Quoting the example given by @Wtower.

def random_string():
    return str(random.randint(10000, 99999))

class Content(models.Model):
    ......
    unique_url = models.CharField(default = random_string)

But this has a caveat : When you create a field and migrate an existing database the function will run only once and updates with the same ‘random’ number.

For example, If you already have 500 entries in the model. You will have the same string, say ‘548945’, for every unique_url which will kill the whole purpose.

You can overcome this by changing the values of the existing entries in the database. This is one time job and can be done using django shell.

python ./manage.py shell
from appname.models import Content, random_string 
# Change appname and file name accordingly

entries = Content.objects.all()
for entry in entries :
    entry.unique_url = random_string()
    entry.save()

👤Trect

Leave a comment