Django UUID Field does not autocreate with new entry

Question:

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)

Asked By: Ric

||

Answers:

change default = uuid.uuid4 to default = uuid.uuid4()

Answered By: Kauê Oliveira

The default = uuid.uuid4 is a Django ORM default, it’s not something the database will do for you like the auto incrementing for ID. So if you add an entry via the phpmyadmin, it will not set the uuid field.

Answered By: The Pjot

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

Answered By: Always Baked

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

Answered By: Raffaele Grieco
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.