How to delete objects in db only one time in for loop

Question:

I have json with few for loop iterations in each other and i want to know how to delete objects in db only one time on first iteration?

I mean objects.all().delete and then ill create everthing from json

task.py

for i in json:
   for j in i.Information:
      MyModel.objects.filter(date=j.Date).delete()
    
      MyModel.objects.create(a=j.A, b=j.B, date=j.Date() #something like that

In this for loop its deleting everytime objects in my db

json.json

[
    {
        "ObjectGUID": "c655ee88-ab64-11ec-89f3-0a943de6fdd6",
        "ListOfCounterparty": [
            {
                "Date": "2023-03-09",
                "Information": [
                    {
                        "CounterpartyGUID": "c9368f92-bf6e-11ea-359e-0a943de6fdd6",
                        "SectionsGUID": [
                            "c9729e4a-ab64-11ec-89f3-0a943de6fdd6"
                        ],
                        "Number": 8
                    }
                ]
            }
        ]
    }
]
Asked By: Kirill_N

||

Answers:

You can make a list of deleted objects where you will be storing a unique information about each object. ID is always unique information so we can use "ObjectGUID": "c655ee88-ab64-11ec-89f3-0a943de6fdd6" from json as store it in deleted_objects. On every iteration we can check if the object was already deleted and if it was then we can skip onto the next step.

Here is the code:

deleted_items = []
for i in json:
   for j in i.Information:
      my_object = MyModel.objects.filter(date=j.Date)  # your code i didn't touch
      if my_object.ObjectGUID not in deleted_items:
         my_object.delete()
         deleted_items.append(my_object.ObjectGUID)
    
      MyModel.objects.create(a=j.A, b=j.B, date=j.Date()  # your code i didn't touch

I hope this helps. If this doesn’t help please comment on my post so I can fix my answer.

Answered By: BokiX

if you want to delete by datetime then you have to use filter with datetime field.

YourModelName.objects.filter(ModelFieldName=datetime.now()).delete()

In this, you can delete it directly all objects using this query

YourModelNmae.objects.all().delete()
Answered By: Tanveer Ahmad
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.