2015-09-03 2 views
0

У меня есть схема базы данных (которую я не могу изменить) с датами. они определяются как:Ошибка даты sqlalchemy. Аргумент «arg» ожидается STR, но получил INT

+---------------------+------------------+------+-----+---------+----------------+ 
| 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 все работает нормально

+0

Не уверен, если это имеет значение, но ваша схема имеет «access_date», а ваш модель имеет столбец как «date_access». – qwertyuip9

+0

плохой набивка ... крепление сейчас –

ответ

1

Вы используете параметр server_default=, и вместо этого вам необходимо его изменить параметр default=. Дополнительная информация приведена в ссылках на документы ниже.

Возможно, это поможет? (http://docs.sqlalchemy.org/en/rel_1_0/core/defaults.html)

Scalar Defaults

The simplest kind of default is a scalar value used as the default value of a column:

Table("mytable", meta, Column("somecolumn", Integer, default=12)) Above, the value “12” will be bound as the column value during an INSERT if no other value is supplied.

Вы используете server_default параметр

server_default=0 

что объясняется здесь

Server Side Defaults¶

A variant on the SQL expression default is the server_default, which gets placed in the CREATE TABLE statement during a create() operation:

t = Table('test', meta, Column('abc', String(20), server_default='abc'), Column('created_at', DateTime, server_default=text("sysdate"))) A create call for the above table will produce:

CREATE TABLE test ( abc varchar(20) default 'abc', created_at datetime default sysdate) The behavior of server_default is similar to that of a regular SQL default; if it’s placed on a primary key column for a database which doesn’t have a way to “postfetch” the ID, and the statement is not “inlined”, the SQL expression is pre-executed; otherwise, SQLAlchemy lets the default fire off on the database side normally.

+0

so ... и ??????? –

+1

Попробуйте использовать 'default' вместо' server_default' – Alex

+0

спасибо, что работает –

0

Я думаю, что ошибка говорит само за себя

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=False или server_default, но не оба.

Когда вы говорите nullable=False, вы ожидаете, что значение будет указано явно в инструкции INSERT, поэтому server_default не потребуется.

Ото, server_default указывает на то, что это нормально, чтобы не обеспечить значение в вашем INSERT заявление, но сервер БД будет по-прежнему заполнить его с вашим server_default

Смежные вопросы