“Löschen Sie den Inhalt der Tabelle Django” Code-Antworten

Objekt aus Tabelle Django löschen

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

Django fallen alle Tische ab

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

Löschen Sie den Inhalt der Tabelle Django

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

Ähnliche Antworten wie “Löschen Sie den Inhalt der Tabelle Django”

Fragen ähnlich wie “Löschen Sie den Inhalt der Tabelle Django”

Weitere verwandte Antworten zu “Löschen Sie den Inhalt der Tabelle Django” auf Python

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen