Adds delete function at a class level - enables instances of models to be deleted without reading them first
This commit is contained in:
Simon Prickett 2022-02-15 20:28:52 +00:00 committed by GitHub
commit 09a3599a3e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 2 deletions

View file

@ -1114,8 +1114,10 @@ class RedisModel(BaseModel, abc.ABC, metaclass=ModelMeta):
pk = getattr(self, self._meta.primary_key.field.name) pk = getattr(self, self._meta.primary_key.field.name)
return self.make_primary_key(pk) return self.make_primary_key(pk)
async def delete(self): @classmethod
return await self.db().delete(self.key()) async def delete(cls, pk: Any) -> int:
"""Delete data at this key."""
return await cls.db().delete(cls.make_primary_key(pk))
@classmethod @classmethod
async def get(cls, pk: Any) -> "RedisModel": async def get(cls, pk: Any) -> "RedisModel":

View file

@ -375,6 +375,22 @@ async def test_saves_model_and_creates_pk(m):
assert member2 == member assert member2 == member
@pytest.mark.asyncio
async def test_delete(m):
member = m.Member(
first_name="Simon",
last_name="Prickett",
email="s@example.com",
join_date=today,
age=97,
bio="This is a test user to be deleted.",
)
await member.save()
response = await m.Member.delete(member.pk)
assert response == 1
def test_raises_error_with_embedded_models(m): def test_raises_error_with_embedded_models(m):
class Address(m.BaseHashModel): class Address(m.BaseHashModel):
address_line_1: str address_line_1: str

View file

@ -187,6 +187,22 @@ async def test_saves_model_and_creates_pk(address, m, redis):
assert member2.address == address assert member2.address == address
@pytest.mark.asyncio
async def test_delete(address, m, redis):
member = m.Member(
first_name="Simon",
last_name="Prickett",
email="s@example.com",
join_date=today,
age=38,
address=address,
)
await member.save()
response = await m.Member.delete(member.pk)
assert response == 1
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_saves_many_implicit_pipeline(address, m): async def test_saves_many_implicit_pipeline(address, m):
member1 = m.Member( member1 = m.Member(