Home > Blockchain >  How to Add uuid field in django Existing User model?
How to Add uuid field in django Existing User model?

Time:05-13

I really need your help, I've been looking everywhere but can't find anything?

CodePudding user response:

Please before you ask a question, review this section: How to ask a question

If you want to add a UUID field in a model you need to import the following:

import uuid

Then in the model you need to create a new field:

unique_uuid = models.CharField(max_length=1024, null=True, blank=True)

Finally you need to update the default save method of the model:

def save(self, trigger=True, *args, **kwargs):
    if not self.unique_uuid:
        self.unique_uuid = uuid.uuid4()

    super(ModelName, self).save(*args, **kwargs)

CodePudding user response:

Its one of those things where you'd rather not start from here if you want to get there. In the Django doc, look Here

If you already have Django default user objects, then you have to extend using a OneToOne relation to an object of your own definition (it's often called a profile). So add

class Profile( models.Model)
    user = models.OneToOneField( User, on_delete=models.CASCADE, )                          
    uuid = models.UUIDField( default=uuid.uuid4, editable=False)

makemigrations and migrate and you will then be able to refer to user.profile.uuid. The default is a callable so the migration will call it to assign a unique UUID to all existing users (I think).

The doc I linked explains how to change Django admin to handle the profile object.

Anything else you want to add to your users goes in their profile object.

  • Related