Home » Python » How to remove all of the data in a table using django

How to remove all of the data in a table using django

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have two questions :

  1. how to delete the table in django
  2. how to remove all of the data in table

this is my code, but not successful :

Reporter.objects.delete()
Answers:

Inside a manager:

def delete_everything(self):
    Reporter.objects.all().delete()

def drop_table(self):
    cursor = connection.cursor()
    table_name = self.model._meta.db_table
    sql = "DROP TABLE %s;" % (table_name, )
    cursor.execute(sql)

Questions:
Answers:

As per the latest documentation, the correct method to call would be:

Reporter.objects.all().delete()

Questions:
Answers:

If you want to remove all the data from all your tables, you might want to try the command python manage.py flush. This will delete all of the data in your tables, but the tables themselves will still exist.

See more here: https://docs.djangoproject.com/en/1.8/ref/django-admin/

Questions:
Answers:

Django already has a full delete method. You just missed it by one.

Reporter.objects.all().remove()