diff --git a/pyproject.toml b/pyproject.toml index 9b48b36..27e3775 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "redis-om" -version = "0.0.8" +version = "0.0.9" description = "A high-level library containing useful Redis abstractions and tools, like an ORM and leaderboard." authors = ["Andrew Brookins "] maintainers = ["Andrew Brookins "] diff --git a/redis_om/model/model.py b/redis_om/model/model.py index 017f1bb..eaa42c6 100644 --- a/redis_om/model/model.py +++ b/redis_om/model/model.py @@ -1014,6 +1014,7 @@ class ModelMeta(ModelMetaclass): new_class._meta.primary_key_creator_cls = getattr( base_meta, "primary_key_creator_cls", UlidPrimaryKey ) + # TODO: Configurable key separate, defaults to ":" if not getattr(new_class._meta, "index_name", None): new_class._meta.index_name = ( f"{new_class._meta.global_key_prefix}:" @@ -1203,6 +1204,17 @@ class HashModel(RedisModel, abc.ABC): db.hset(self.key(), mapping=document) return self + @classmethod + def all_pks(cls): + key_prefix = cls.make_key(cls._meta.primary_key_pattern.format(pk="")) + # TODO: We assume the key ends with the default separator, ":" -- when + # we make the separator configurable, we need to update this as well. + # ... And probably lots of other places ... + return ( + key.split(":")[-1] + for key in cls.db().scan_iter(f"{key_prefix}*", _type="HASH") + ) + @classmethod def get(cls, pk: Any) -> "HashModel": document = cls.db().hgetall(cls.make_primary_key(pk)) diff --git a/tests/test_hash_model.py b/tests/test_hash_model.py index 2b4201d..4e8f2c3 100644 --- a/tests/test_hash_model.py +++ b/tests/test_hash_model.py @@ -411,6 +411,12 @@ def test_sorting(members, m): m.Member.find().sort_by("join_date").all() +def test_all_keys(members, m): + pks = sorted(list(m.Member.all_pks())) + assert len(pks) == 3 + assert pks == sorted([m.pk for m in members]) + + def test_not_found(m): with pytest.raises(NotFoundError): # This ID does not exist.