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

后端 未结 8 1763
执笔经年
执笔经年 2020-12-12 21:12

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 succe

8条回答
  •  再見小時候
    2020-12-12 21:54

    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

提交回复
热议问题