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

六月ゝ 毕业季﹏ 提交于 2020-08-24 05:56:30

问题


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?


回答1:


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)



回答2:


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()



来源:https://stackoverflow.com/questions/33588668/how-to-set-a-random-integer-as-the-default-value-for-a-django-charfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!