在使用 SQLModel 进行模型定义的时候,使用 description 属性来定义一个 Field 的描述信息。不过在数据库中,用的是 comment。SQLModel 在生成建表语句的时候,默认不会生成 comment 信息,需要使用 sa_column_kwargs={“comment”: “字段说明信息”} 来单独定义 comment,这样会在一个字段的定义上有两个重复的定义。在 https://github.com/tiangolo/sqlmodel/issues/492 这个 issue 中有人写了一个转换程序,摘抄如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Automatically set comment to Column using description.
# https://github.com/tiangolo/sqlmodel/issues/492
class DescriptionMeta(SQLModelMetaclass):
""" 将 description作为字段的comment """
def __new__(
cls,
name: str,
bases: Tuple[Type[Any], ...],
class_dict: Dict[str, Any],
**kwargs: Any,
) -> Any:
new_class = super().__new__(cls, name, bases, class_dict, **kwargs)
fields = new_class.model_fields
for k, field in fields.items():
desc = field.description
if desc:
# deal with sa_column_kwargs
if field.sa_column_kwargs is not PydanticUndefined:
field.sa_column_kwargs["comment"] = desc
else:
field.sa_column_kwargs = {"comment": desc}
# deal with sa_column
if field.sa_column is not PydanticUndefined:
if not field.sa_column.comment:
field.sa_column.comment = desc
# deal with attributes of new_class
if hasattr(new_class, k):
column = getattr(new_class, k)
if hasattr(column, "comment") and not column.comment:
column.comment = desc
return new_class