如何使用SQLAlchemy在MySQL中为表或列添加注释?

13

我希望为模型创建的表格和列添加注释。我尝试使用Column类的doc参数,如下所示:

class Notice(db.Model):
    __tablename__ = "tb_notice"
    __table_args__ = {'mysql_engine': 'MyISAM'}

    seqno = db.Column(db.Integer, primary_key=True, autoincrement=True, doc="seqno")
    title = db.Column(db.String(200), nullable=False, doc="notice title")
    detail = db.Column(db.TEXT, nullable=True, doc="notice detail ")

但它没有起作用,注释没有被添加到SQL创建语句中,我想知道如何向表中添加注释。

3个回答

10
根据doc参数的文档说明:

doc¶ - 可选的字符串,可用于ORM或类似工具文档化Python端上的属性。 该属性不会呈现SQL注释;用Column.comment参数代替。

comment参数如下:

comment¶ - 可选的字符串,在表创建时渲染为SQL注释。

请注意,自SQlAlchemy版本1.2起添加了comment
如果要为表添加注释,只需将附加的comment属性(根据Table类的文档)传递给您的__table_args__字典。也是从版本1.2开始添加的。
代码应该像这样:
class Notice(db.Model):
    
    __tablename__ = "tb_notice"
    __table_args__ = {
        'mysql_engine': 'MyISAM',
        'comment': 'Notice table'
    }

    seqno = db.Column(db.Integer, primary_key=True, autoincrement=True, doc="seqno",
                      comment='Integer representing the sequence number')
    title = db.Column(db.String(200), nullable=False, doc="notice title",
                      comment='Title of the notice, represented as a string')
    detail = db.Column(db.TEXT, nullable=True, doc="notice detail",
                       comment='Notice detail description')

doc 属性充当您的类的文档字符串:

print(Notice.title.__doc__)

将输出:

通知标题

现在对应的 SQL 表创建语句如下:

CREATE TABLE `tb_notice` (
  `seqno` int(11) NOT NULL COMMENT 'Integer representing the sequence number',
  `title` varchar(200) NOT NULL COMMENT 'Title of the notice, represented as a string',
  `detail` text COMMENT 'Notice detail description'
) ENGINE=MyISAM DEFAULT CHARSET=utf32 COMMENT='Notice table';

你可以看到注释已经正确地添加到了表格和列中。

8

1
链接很好,但最好的答案应该是自包含的,因此像@rho编写的示例会大大改善这个问题。 - Ilja Everilä

4
在新的1.2版本中,您可以进行以下操作:
class Notice(db.Model):
    __tablename__ = "tb_notice"
    __table_args__ = {
        'mysql_engine': 'MyISAM'
        'comment': 'yeah comment'
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接