Home > Enterprise >  How to revert back data entry if second query fails
How to revert back data entry if second query fails

Time:09-26

Heres my code:

data = {
    "order_type":"order",
    "user_id":user_id,
    "order_total":order_total,
    ...
}
serialzier = UserOrderSer(data=data)
if serialzier.is_valid(raise_exception=True):
    serialzier.save()

product_data = []
for i in all_response:
    product_data.append({
        "order_id": serialzier.data['order_id'],
        "product_id":i['product_id'],
        "product_name":i['product_name'],
        "product_price": i['selling_price'],
        ...
    })

product_serializer = UserOrderProductSer(data=product_data,many=True)
if product_serializer.is_valid(raise_exception=True):
    product_serializer.save()

If the product_serializer.is_valid fails, then i want the serialzier = UserOrderSer(data=data) entry to revert back. Since, i'm using id of 1st entry in 2nd entry i cannot check .is_valid both at same time

CodePudding user response:

DOCS

Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

You can use transaction.atomic()

  • Related