“Hapus konten tabel django” Kode Jawaban

Hapus objek dari tabel django

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

Django menjatuhkan semua meja

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

Hapus konten tabel django

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

Jawaban yang mirip dengan “Hapus konten tabel django”

Pertanyaan yang mirip dengan “Hapus konten tabel django”

Lebih banyak jawaban terkait untuk “Hapus konten tabel django” di Python

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya