Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a random integer as the default value for a Django CharField?

My models.py looks like this:

import random
random_string = str(random.randint(10000, 99999))

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

When I add a content in admin, an integer in the range is generated and put into the charfield as its default value. From there, I can simple add more words to the charfield. However, the problem with my current set-up is that the integer remains the same every time I add a new article. I want to generate and insert the random integer as I am using the unique_url field to basically find each of my specific objects, and I am expecting a lot of content, so adding the random number will generally ensure that each content has a one of a kind unique_url.

Therefore, I am looking for a system which generates a random integer everytime a new content is added using the admin panel, and puts it as the default of one the fields. Is such a thing even possible in Django?

like image 457
darkhorse Avatar asked Nov 07 '15 22:11

darkhorse


People also ask

How do you generate unique random numbers in Django?

randint() method is used to generate a random number between the start and stop.

What does CharField mean in Django?

CharField is a commonly-defined field used as an attribute to reference a text-based database column when defining Model classes with the Django ORM. The Django project has wonderful documentation for CharField and all of the other column fields.


1 Answers

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)
like image 77
Wtower Avatar answered Sep 28 '22 04:09

Wtower