-1

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. E.g ABYpsB

Please help needed

Josias Aurel
  • 37
  • 1
  • 7
  • Does this answer your question? [Generate a Unique String in Python/Django](https://stackoverflow.com/questions/26030811/generate-a-unique-string-in-python-django) – mkrieger1 Aug 09 '20 at 09:27
  • It doesn't really do the work. Yes, it generates a random string (just like my function) but it's not random at the creation of a new URL. When I create new URLs in the admin, they all have the same random string which doesn't solve my problem. Thanks anyway - I found a better way of generating the strings – Josias Aurel Aug 09 '20 at 09:39

1 Answers1

0

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 .

Dharman
  • 30,962
  • 25
  • 85
  • 135
Gautamrk
  • 1,144
  • 9
  • 12