I am working on a Django project and I want to make a field to always be randomly generated so they are unique in the database but I don't seem to get how to do so. I tried the following:
from django.db import models
# Random character generation for
# the unique short URLs
import string, random
def random_url(n):
return ''.join(random.choice(string.ascii_letters) for x in range(n))
#print(random_id(6)) #testing the function
#Class for the URL
class ShortURL(models.Model):
original_url = models.CharField(max_length=200)
short_url = models.CharField(max_length=100, primary_key=True, default=random_url(6))
timestamp = models.DateTimeField(auto_now=True)
In my admin view. All the "URL" have the same random code which I don't want. Eg ABYpsB
Please help needed
Django has the UUID field that generates random ids
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
it will generate unique id as per request.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.