How to keep deleted rows from table in variable in Django

Question:

I want to delete all the rows in a tables but before that I want to store the old data and do some operation between old and new data.

This is what I have tried.

old_data = Rc.object.all()
Rc.object.all().delete()
# Now I fetch some api and apply saving operation on table

I have noticed that data in old_data is updated to the new data.
To test this I have done some thing like this

for rows in old_data:
  check = Rc.object.filter(Q(id=dt.id)&Q(modified_date__gt=rows.modified_date)).exist()
  print(check)

I found check is always false (rows with that id exists in the table)
But when I print each rows in old_data just after old_data = Rc.object.all(), old_data remains same(check becomes true) and does not updated to the new data.

Is there something I am missing? How can I store all rows in the variable and then delete the rows ? Please help.

Asked By: Anonymous

||

Answers:

For this you need to understand how and when Django execute the command:

In your below code :

old_data = Rc.object.all()
Rc.object.all().delete()
# Now I fetch some api and apply saving operation on table

the line old_data = Rc.object.all() is just an expression and would not be executed until you are using the old_data.
For example :
if you insert the line len(old_data) or print(old_data), the values would be stored.

QuerySets are evaluated only if you "consume" the queryset.

Answered By: trigo
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.