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)
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()
- Django Nested Groups: Groups in Groups
- Enabling Django Admin Filters on Many-to-Many Fields
- How to execute code on post_migrate signal in Django?
- How to return data with 403 error in Django Rest Framework?
- How to see exception generated into django template variable?