-
Hi, I don't know well about the database, but I'd like to make a table where the entries PK should be UUID, generated from its String field. The string can have varying length so it's not suitable to use it directly as an id. Or at least I need to use any other hash like md5 or sha1 since I want to make the id unique depending only on the string, not from the system or DNS. I'd like to make it id autogenerated once the string is valid from the pydantic's validator. Is it possible in ormar? Thank you so much! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 30 replies
-
You can use signals for it. If you register 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 that string is stored in a database only once, you can still autogenerate uuids and simply add unique=True constraint on your string column. That way even if you pass a model with different pk but same string you will get an exception. |
Beta Was this translation helpful? Give feedback.
-
Hmm.. I found that when I use self = <Connection(Thread-2, started 140397017454336)>
def run(self) -> None:
"""
Execute function calls on a separate thread.
:meta private:
"""
while True:
# Continues running until all queue items are processed,
# even after connection is closed (so we can finalize all
# futures)
try:
future, function = self._tx.get(timeout=0.1)
except Empty:
if self._running:
continue
break
try:
LOG.debug("executing %s", function)
> result = function()
E sqlite3.IntegrityError: NOT NULL constraint failed: mols.id
../../../.pyenv/versions/3.9.5/envs/kai/lib/python3.9/site-packages/aiosqlite/core.py:102: IntegrityError It looks like
to use |
Beta Was this translation helpful? Give feedback.
-
Fixed in 0.10.12 (via #251) |
Beta Was this translation helpful? Give feedback.
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.
Don't know what exactly is your use case but if you want to ensure th…