“Usuń zawartość tabeli Django” Kod odpowiedzi

Usuń obiekt z tabeli Django

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

Django upuść wszystkie tabele

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

Usuń zawartość tabeli Django

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

Odpowiedzi podobne do “Usuń zawartość tabeli Django”

Pytania podobne do “Usuń zawartość tabeli Django”

Więcej pokrewnych odpowiedzi na “Usuń zawartość tabeli Django” w Python

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu