Skip to content
Advertisement

How to update a single value in redis hash

I’m using Python FastAPI with redis. I wrote a function to update values in a redis hash, but I couldn’t able to update a single value alone, I could only able to re-write the whole hash.

My model:

class Item4(BaseModel):
    balance: Optional[float] = None
    currencyCode: Optional[str] = None
    customerId: Optional[int] =None

My function:

@app.put("/updateBalance/{balanceId}")
async def update_item(item: Item4, balanceId):
    msg = r.hmset(balanceId, dict(item))
    return msg

Advertisement

Answer

hmset is deprecated for hset – but if you want to only update a single key, do not send an hash with all the keys present.

You can use the exclude_unset parameter to Pydantic’s dict() method to not include any values that hasn’t been explicitly provided:

r.hmset(balanceId, item.dict(exclude_unset=True))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement