[python] How to remove all of the data in a table using Django

I have two questions:

  1. How do I delete a table in Django?
  2. How do I remove all the data in the table?

This is my code, which is not successful:

Reporter.objects.delete()

This question is related to python django django-queryset

The answer is


Django 1.11 delete all objects from a database table -

Entry.objects.all().delete()  ## Entry being Model Name. 

Refer the Official Django documentation here as quoted below - https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects

Note that delete() is the only QuerySet method that is not exposed on a Manager itself. This is a safety mechanism to prevent you from accidentally requesting Entry.objects.delete(), and deleting all the entries. If you do want to delete all the objects, then you have to explicitly request a complete query set:

I myself tried the code snippet seen below within my somefilename.py

    # for deleting model objects
    from django.db import connection
    def del_model_4(self):
        with connection.schema_editor() as schema_editor:
            schema_editor.delete_model(model_4)

and within my views.py i have a view that simply renders a html page ...

  def data_del_4(request):
      obj = calc_2() ## 
      obj.del_model_4()
      return render(request, 'dc_dash/data_del_4.html') ## 

it ended deleting all entries from - model == model_4 , but now i get to see a Error screen within Admin console when i try to asceratin that all objects of model_4 have been deleted ...

ProgrammingError at /admin/dc_dash/model_4/
relation "dc_dash_model_4" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "dc_dash_model_4" 

Do consider that - if we do not go to the ADMIN Console and try and see objects of the model - which have been already deleted - the Django app works just as intended.

django admin screencapture


You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

Use this syntax to delete the rows also to redirect to the homepage (To avoid page load errors) :

def delete_all(self):
  Reporter.objects.all().delete()
  return HttpResponseRedirect('/')

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

Reporter.objects.all().delete()

There are a couple of ways:

To delete it directly:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

instance1 = SomeModel.objects.get(id=id)
instance1.delete()

// don't use same name


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/


Using shell,

1) For Deleting the table:

python manage.py dbshell
>> DROP TABLE {app_name}_{model_name}

2) For removing all data from table:

python manage.py shell
>> from {app_name}.models import {model_name}
>> {model_name}.objects.all().delete()

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to django-queryset

Django values_list vs values Get the latest record with filter in Django How to do a less than or equal to filter in Django queryset? How can I filter a Django query with a list of values? How to obtain a QuerySet of all rows, with specific fields for each one of them? How to perform OR condition in django queryset? Getting a count of objects in a queryset in django How do I filter query objects by date range in Django? How to remove all of the data in a table using Django Select DISTINCT individual columns in django?