sqlalchemy日期错误。争论'arg'是STR,但是得到了INT

时间:2015-09-03 19:12:30

标签: python sqlalchemy

我有一个日期数据库架构(我无法更改)。它们被定义为:

+---------------------+------------------+------+-----+---------+----------------+
| Field               | Type             | Null | Key | Default | Extra          |
+---------------------+------------------+------+-----+---------+----------------+
| id                  | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
...
| access_date         | int(10) unsigned | NO   |     | 0       |                |
+---------------------+------------------+------+-----+---------+----------------+

现在,我的模型定义如下:

 from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class logme(Base):

  id_ = Column(Integer, primary_key=True)
  ...
  access_date = Column(Integer, nullable=False, server_default=0)

当我加载模型时,我收到此错误:

sqlalchemy.exc.ArgumentError: Argument 'arg' is expected to be one of type '<class 'str'>' or '<class 'sqlalchemy.sql.elements.ClauseElement'>' or '<class 'sqlalchemy.sql.elements.TextClause'>', got '<class 'int'>'

如果我注释掉access_date,一切正常

2 个答案:

答案 0 :(得分:3)

您正在使用server_default=参数,而是需要将其更改为使用default=参数。以下文档链接中的更多信息。

也许这会有所帮助? (http://docs.sqlalchemy.org/en/rel_1_0/core/defaults.html

  

标量默认值

     

最简单的默认值是用作默认值的标量值   列的值:

     

表(“mytable”,meta,       列(“somecolumn”,整数,默认 = 12))上面,如果没有其他值,则值“12”将在INSERT期间绑定为列值   提供。

您正在使用server_default参数

server_default=0

这里解释

  

服务器端默认值

     

SQL表达式默认的变体是server_default,它是   在create()操作期间被置于CREATE TABLE语句中:

     

t =表('test',meta,       列('abc',String(20),server_default ='abc'),       列('created_at',DateTime,server_default = text(“sysdate”)))上表的创建调用将产生:

     

CREATE TABLE test(       abc varchar(20)默认'abc',       created_at datetime default sysdate)server_default的行为类似于常规SQL默认行为;如果它是   放在数据库的主键列上,没有办法   to“postfetch”ID,并且语句不是“内联”的SQL   表达式是预先执行的;否则,SQLAlchemy会使用默认值   正常在数据库端启动。

答案 1 :(得分:1)

我认为错误是不言自明的

Argument 'arg' is expected to be one of type '<class 'str'>' ....
got '<class 'int'>'

按如下方式更改行:

access_date = Column(Integer, nullable=False, server_default="0")

请将报价置于零附近。由于列定义为Integer,因此服务器端默认值为数字零,而不是字符串“0”

在不相关的说明中,我认为您需要nullable=Falseserver_default,而不是两者。

当您说nullable=False时,您希望在INSERT语句中明确提供值,因此不需要server_default

OTOH,server_default表示可以在INSERT语句中提供值,但DB服务器仍会使用server_default

填充它