“Supprimer le contenu de la table Django” Réponses codées

Supprimer l'objet de la table Django

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

Django dépose toutes les tables

The following is a function to drop all the public tables from the
database using: python manage.py dropalltables

1 - In the app that contains the models, create:
  management/commands/dropalltables.py

The tree structure should look like this:
  my_app
     |---management
             |---commands
                     |---dropalltables.py

        
2 - in dropalltables.py write:
  
from django.core.management.base import BaseCommand, CommandError
from django.db import connection


class Command(BaseCommand):
    help = "Drop all the tables from the database"

    def handle(self, *args, **options):
        try:
            print("Do you really want to DROP (delete) ALL THE PUBLIC TABLES from the database?")
            choice = input("type the following sentence to confirm: yes, drop all! ")
            if choice.lower() == "yes, drop all!":
                cursor = connection.cursor()
                cursor.execute("SELECT table_name FROM INFORMATION_SCHEMA.tables where table_schema = 'public';")
                parts = ('DROP TABLE IF EXISTS %s CASCADE;' % table for (table,) in cursor.fetchall())
                sql = '\n'.join(parts) + '\n'
                connection.cursor().execute(sql)
                print("Done! There are no more public tables in the database.")
            else:
                print("You have chosen not to remove the tables.")

        except Exception as e:
            raise CommandError(f"Error: {e}")

3 - In the terminal type:
  python manage.py dropalltables
Puzzled Penguin

Supprimer le contenu de la table Django

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

Réponses similaires à “Supprimer le contenu de la table Django”

Questions similaires à “Supprimer le contenu de la table Django”

Plus de réponses similaires à “Supprimer le contenu de la table Django” dans Python

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code