Closed
Description
Hey everyone, I am trying to store and fetch in a model whose field's type is boolean. However, as you may know, Redis will complain about that when trying to encode bool values. But, I found a workaround for this use case, take the following as an example using the sync version redis_om
:
from typing import Optional
from redis_om import Field, HashModel, JsonModel, Migrator
class Author(HashModel):
first_name: str = Field(index=True)
last_name: str
active: Optional[bool] = Field(index=True, default=False)
class Blog(JsonModel):
title: str = Field(index=True, full_text_search=True)
content: str
author: Author
Migrator().run()
author = Author(
first_name="Mahmoud",
last_name="Harmouch",
).save()
blog = Blog(
title="Redis",
content="Redis is a blazingly fast k/v store!",
author=author
)
blog.save()
print(blog.pk)
assert Blog.find(Blog.pk == blog.pk).all()) == blog
Running this above script will throw the following exception:
redis.exceptions.DataError: Invalid input of type: 'bool'. Convert to a bytes, string, int or float first.
However, if you are using the async version, storing and indexing will work if the type is str
. So to make boolean values work in aredis_om
, just replace str
in place of bool
:
class Author(HashModel):
first_name: str = Field(index=True)
last_name: str
active: Optional[str] = Field(index=True, default=False)
class Blog(JsonModel):
title: str
content: str
author: Author = Field(index=True)
And your endpoints call async functions like the following to create/fetch k/v:
async def get_blogs(author: Optional[Author] = None):
if not author:
return await Author.find().all()
else:
return await Author.find(Author.author == author).all()
async def create_author(request: Request):
return await Author(first_name=request.first_name, last_name=request.last_name, active=request.active).save()
# or simply: return await Author(**request).save() if request is a dict.
Just wanted to share in case someone might find it helpful.
Metadata
Metadata
Assignees
Labels
No labels