django | 根據 model 建立對應的表

kingron發表於2024-06-25

程式碼如下:

   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

  1. SchemaEditor | Django documentation | Django (djangoproject.com)
  2. python - How to programmatically generate the CREATE TABLE SQL statement for a given model in Django? - Stack Overflow

相關文章