I have a model in Django that looks like this:
class Video(models.Model):
id = models.CharField(primary_key=True, default=uuid.uuid4().hex[:8], editable=False, max_length=8)
title = models.TextField(max_length=100, help_text='Insert video title here', verbose_name='Title')
I have a superuser that can create new Videos. I go into the admin view and create a new Video. Lets say I create a Video titled "Video 1". It shows up correctly.
Then, if I create another video called Video 2, I can only see Video 2 in the list of Videos. I looked at the history of Video 2, and here is what it said:
March 25, 2018, 3:37 p.m. superuser Added.
March 25, 2018, 3:37 p.m. superuser Changed title.
Which means that Video 1 is just being updated to Video 2.
However, if I restart my server, I'm able to see Video 2, and then I'm able to create a different Video. But then the problem persists with this new video.
The way I understand it is that with each server session, I'm only allowed to create a single entry.
答案 0 :(得分:3)
Your default is being evaluated once when the server starts and the model is loaded:
class Video(models.Model):
id = models.CharField(primary_key=True, default=uuid.uuid4().hex[:8], editable=False, max_length=8)
You should define a function that generates the default instead:
def new_id():
return uuid.uuid4().hex[:8]
class Video(models.Model):
id = models.CharField(primary_key=True, default=new_id, editable=False, max_length=8)
Since you are truncating the UUID, you should consider whether there is a realistic chance of collisions (especially since it appears that collisions overwrite old data silently). You might be better using the default AutoField
primary key or a full UUIDField
. You could even add an extra 8-character video_id
field to display to users.