Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redis-om python custom primary key

I've been trying to create a custom PK based on fields in the model. https://redis.io/learn/develop/python/redis-om

"The default ID generation function creates ULIDs, though you can change the function that generates the primary key for models if you'd like to use a different kind of primary key."

I would like to customise the generation of primary keys based on some of the fields of the model (instance).

I noticed that if I create a field called "pk," redis-om does take this value as the primary key.

But is there a way. I can just declaratively assign fields as primary keys?

like image 733
AmitGK Avatar asked Apr 11 '26 12:04

AmitGK


1 Answers

You can add Field(primary_key=True) to any of the attributes in your model.

Here is the code provided in their example with the default pk:

import datetime
from typing import Optional

from redis_om import HashModel


class Customer(HashModel):
    first_name: str
    last_name: str
    email: str
    join_date: datetime.date
    age: int
    bio: Optional[str] = "Super dope"


andrew = Customer(
    first_name="Andrew",
    last_name="Brookins",
    email="[email protected]",
    join_date=datetime.date.today(),
    age=38)

print(andrew.pk)
# > '01FJM6PH661HCNNRC884H6K30C'

andrew.save()
assert Customer.get(andrew.custom_pk) == andrew

To assign your own primary key, you would update the code as follows:

import datetime
from typing import Optional

from redis_om import HashModel, Field


class Customer(HashModel):
    custom_pk:str = Field(primary_key=True)
    first_name: str
    last_name: str
    email: str
    join_date: datetime.date
    age: int
    bio: Optional[str] = "Super dope"


andrew = Customer(
    custom_pk = "customPkValue",
    first_name="Andrew",
    last_name="Brookins",
    email="[email protected]",
    join_date=datetime.date.today(),
    age=38)
    
andrew.save()

assert Customer.get(andrew.custom_pk) == andrew
like image 153
Jacob Frank Avatar answered Apr 13 '26 02:04

Jacob Frank