Ticket #36039: export_table_info.py

File export_table_info.py, 1.4 KB (added by Arian Omrani, 23 hours ago)
Line 
1from django.core.management.base import BaseCommand
2from django.db import connection
3from django.apps import apps
4
5
6class Command(BaseCommand):
7 help = "Prints and saves all table names and columns from all apps"
8
9 def handle(self, *args, **kwargs):
10 # File to save the output
11 output_file = "table_info.txt"
12
13 with connection.cursor() as cursor:
14 self.stdout.write("Fetching all table names and columns...\n")
15 data = []
16
17 for model in apps.get_models():
18 # Get table name
19 table_name = model._meta.db_table
20 # Get columns from the database
21 cursor.execute(f"PRAGMA table_info({table_name});")
22 columns = cursor.fetchall()
23
24 # Process columns
25 column_names = [column[1] for column in columns] # Adjust index as per your DB dialect
26 data.append(f"Table: {table_name}\nColumns: {', '.join(column_names)}\n")
27
28 # Print the table info
29 self.stdout.write(f"Table: {table_name}")
30 self.stdout.write(f"Columns: {', '.join(column_names)}\n")
31
32 # Save to a file
33 self.stdout.write(f"\nSaving data to {output_file}...")
34 with open(output_file, "w") as file:
35 file.writelines(data)
36
37 self.stdout.write(self.style.SUCCESS("Operation completed successfully."))
Back to Top