Django InspectDB 缺少mysql/mariadb的注释问题。

已完成: 字段的comment作为 verbose_name
未完成: 表名的comment作为 表的verbose_name

环境: django@3.13.1。
修改2处文件。

1.django\core\management\commands\inspectdb.py
2.django\db\backends\mysql\introspection.py

1.inspectdb.py

@@ -213,6 +213,8 @@ class Command(BaseCommand):
                         field_desc += ", ".join(
                             "%s=%r" % (k, v) for k, v in extra_params.items()
                         )
+                    if row.column_comment:
+                        field_desc += f", verbose_name='{row.column_comment}'"
                     field_desc += ")"
                     if comment_notes:
                         field_desc += "  # " + " ".join(comment_notes)

2.introspection.py

@@ -10,11 +10,11 @@ from django.db.models import Index
 from django.utils.datastructures import OrderedSet
 
 FieldInfo = namedtuple(
-    "FieldInfo", BaseFieldInfo._fields + ("extra", "is_unsigned", "has_json_constraint")
+    "FieldInfo", BaseFieldInfo._fields + ("column_comment", "extra", "is_unsigned", "has_json_constraint")
 )
 InfoLine = namedtuple(
     "InfoLine",
-    "col_name data_type max_len num_prec num_scale extra column_default "
+    "col_name data_type max_len num_prec num_scale extra column_default column_comment "
     "collation is_unsigned",
 )
 
@@ -116,11 +116,12 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
         #   not visible length (#5725)
         # - precision and scale (for decimal fields) (#5014)
         # - auto_increment is not available in cursor.description
+        # numeric_precision, numeric_scale, extra, column_default,
         cursor.execute(
             """
             SELECT
                 column_name, data_type, character_maximum_length,
-                numeric_precision, numeric_scale, extra, column_default,
+                numeric_precision, numeric_scale, extra, column_default, column_comment,
                 CASE
                     WHEN collation_name = %s THEN NULL
                     ELSE collation_name
@@ -134,7 +135,8 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
             """,
             [default_column_collation, table_name],
         )
-        field_info = {line[0]: InfoLine(*line) for line in cursor.fetchall()}
+        fetchall = cursor.fetchall()
+        field_info = {line[0]: InfoLine(*line) for line in fetchall}
 
         cursor.execute(
             "SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name)
@@ -155,6 +157,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
                     line[6],
                     info.column_default,
                     info.collation,
+                    info.column_comment,
                     info.extra,
                     info.is_unsigned,
                     line[0] in json_constraints,
posted @ 2022-09-29 18:36  wgf4242  阅读(48)  评论(0编辑  收藏  举报