instance.delete() not work as expected
Closed this issue · 2 comments
JoshYuJump commented
I am working on a API of deleting a single resource named product
.
DELETE /products/1
Part of the code is
@router.delete('/product/{row_id}')
async def delete_product(row_id: str):
product = await Product.objects().where(Product.id == row_id)
await product.delete()
It don't work and raise a exception remind me added where clause
raise DeletionError(
"Do you really want to delete all the data from "
f"{classname}? If so, use {classname}.delete(force=True). "
"Otherwise, add a where clause."
)
sinisaos commented
@JoshYuJump You have 2 ways to delete a record.
- As a query builder with delete method
@router.delete('/product/{row_id}')
async def delete_product(row_id: str):
await Product.delete().where(Product.id == row_id)
- As an ORM with objects
@router.delete('/product/{row_id}')
async def delete_product(row_id: str):
product = await Product.objects().where(Product.id == row_id).first()
# you can also use get() method like this to get single object
# product = await Product.objects().get(Product.id == row_id)
await product.remove() # a proxy to a delete query
Hope that helps.
JoshYuJump commented
@sinisaos Thanks a lot, It was so helpful to me.