程式碼如下:
from django.db import connections
with connections['db_to_create_a_table_in'].schema_editor() as schema_editor:
schema_editor.create_model(YourUnmanagedModelClass)
可透過錯誤捕獲實現 create table if not exist
的效果。
Reference
- SchemaEditor | Django documentation | Django (djangoproject.com)
- python - How to programmatically generate the CREATE TABLE SQL statement for a given model in Django? - Stack Overflow