Skip to content

How to make an UUID PK generated by String field? #230

Answered by collerek
jinserk asked this question in Q&A
Discussion options

You must be logged in to vote

You can use signals for it.

If you register pre_save signal you can register a function that will generate uuid from string for you.
You can use uuid3 or uuid5 to generate md5 or sha1 out of string.

Pre_save is triggered before the save happens in db. Check signals docs section.

Something like this.

# model class is your model - one signal can work for several classes - pass a list in that case
@pre_save(ModelClass)
async def before_save(self, sender, instance, **kwargs):
        # string column is a column with your string, pk is a shortcut for primary key column
        instance.pk = uuid.uuid5(instance.string_column)

Don't know what exactly is your use case but if you want to ensure th…

Replies: 3 comments 30 replies

Comment options

You must be logged in to vote
27 replies
@collerek
Comment options

@jinserk
Comment options

@collerek
Comment options

@jinserk
Comment options

@jinserk
Comment options

Answer selected by collerek
Comment options

You must be logged in to vote
2 replies
@collerek
Comment options

@jinserk
Comment options

Comment options

You must be logged in to vote
1 reply
@jinserk
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants