can you use a function to set a field when creating a model (django)

Viewed 27

I have created a model called 'Video' and in the Video class there is a field called videoID. I want videoID to be a randomly generated string but in my solution, there has been some errors. Here is my solution:

models.py

from django.db import models
from django.contrib.auth.models import User
from other.video import generateVideoID

class Video(models.Model):
    videoID = models.TextField(default=generateVideoID(),editable=False)
    author = models.ForeignKey(User,on_delete=models.CASCADE, null=True)

As you can see in the videoID field I have set the default value to a function that returns a random string. This doesn't work because every time I create an object the videoID has the same string. This is the 'generateVideoID' function:

def generateVideoID():
    import random,string

    chars = string.ascii_letters+string.digits+"_-~"

    videoID = ""
    for i in range(12):
        videoID += random.choice(chars)
    return videoID

I have tried to use the 'init' method to set the videoID but that doesn't work. Can anyone help me?

2 Answers

Yes, but you should not call it, and furthermore it should be defined before you refer to it, so:

from django.db import models
from django.contrib.auth.models import User
from other.video import generateVideoID

class Video(models.Model):
    videoID = models.TextField(default=generateVideoID, editable=False)
    author = models.ForeignKey(User,on_delete=models.CASCADE, null=True)

so without parenthesis. If you add parenthesis, the function will be called, and the result will be used as default for all objects.

Alternatively you could use the UUIDField:

from uuid import uuid4

class Video(models.Model):
    uuid = models.UUIDField(default=uuid4, editable=False, unique=True)
    author = models.ForeignKey(User,on_delete=models.CASCADE, null=True)
Related