Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to keep deleted rows from table in variable in Django

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading