如何使用SQLAlchemy在mysql中向表或列添加注释?

ash*_*h84 6 mysql sqlalchemy flask-sqlalchemy

我想添加一个tabble和列创建的注释.

所以我将doc参数添加到SQLAlchemy Column类的构造函数中.

但是不要在列中添加注释.

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 ")
Run Code Online (Sandbox Code Playgroud)

我想知道如何添加表的注释.

Res*_*awi 10

根据参数文档doc

\n
\n

doc\xc2\xb6 \xe2\x80\x93 可选 可由 ORM 使用的字符串或类似于 Python 端的文档属性。该属性不渲染SQL注释;为此目的,请使用 Column.comment 参数。

\n
\n

以及comment参数:

\n
\n

comment\xc2\xb6 \xe2\x80\x93 可选字符串,将在表创建时呈现 SQL 注释。

\n
\n

请注意,comment在 1.2 版本中添加了SQlAlchemy

\n

为了添加表的注释,您只需将附加comment属性(根据Table文档)传递给您的__table_args__字典。1.2版本中也添加了

\n

代码会是这样的:

\n
class Notice(db.Model):\n    \n    __tablename__ = "tb_notice"\n    __table_args__ = {\n        \'mysql_engine\': \'MyISAM\',\n        \'comment\': \'Notice table\'\n    }\n\n    seqno = db.Column(db.Integer, primary_key=True, autoincrement=True, doc="seqno",\n                      comment=\'Integer representing the sequence number\')\n    title = db.Column(db.String(200), nullable=False, doc="notice title",\n                      comment=\'Title of the notice, represented as a string\')\n    detail = db.Column(db.TEXT, nullable=True, doc="notice detail",\n                       comment=\'Notice detail description\')\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
print(Notice.title.__doc__)\n
Run Code Online (Sandbox Code Playgroud)\n

将输出:\nnotice title

\n

现在相应的SQL建表语句是:

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

您可以看到注释已正确添加到表和列中。

\n