I just added a new model where I want to use a UUID for the first time.
I run Django 3.1.3 on python 3.8.10.
Found some questions about this and I am quite certain I did it according to those suggestions. However, when I add an entry to that model (in phpmyadmin web-surface) the UUID is not being added, it just stays empty. However when I create an other one I get the error, that the UUID Field is not allowed to be the same as somewhere else (both empty) which means at least the unique=True does work.
Another thing to mention is, when I create the field using VSCode, normally those fieldnames are being auto-completed, however it is not the case with this one. Thought this might give you a hint what is going on.
My model looks like this:
from django.db import models
import uuid
class MQTTTable(models.Model):
uuid = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False, unique = True)
description = models.CharField(max_length= 100, default = None)
clientID = models.CharField(max_length = 50, default = None)
mastertopic = models.CharField(max_length = 200, default = None)
4
Answers
change
default = uuid.uuid4
todefault = uuid.uuid4()
The
default = uuid.uuid4
is a Django ORM default, it’s not something the database will do for you like the auto incrementing forID
. So if you add an entry via the phpmyadmin, it will not set the uuid field.You will be needing to make migration like this in order to populate the fields for existing entries. Visit this to learn how to do that. With creation of new objects the field is auto populated using the python way. Thanks
Migrations that add unique fields
You can visit this question which may help you with your answer:
Automatically fill pre-existing database entries with a UUID in Django
Basically, you can’t add an entry in the php admin panel and expect that django adds the UUID, because it is sets by Django and not by the database. You can try to implement a function in the model.py file and serialize it as source of a Charfield, however in this case you need django rest framework