Reputation: 674
I have created a table using the following query,
CREATE TABLE user_account (
user_id serial PRIMARY KEY,
user_name VARCHAR ( 50 ) UNIQUE NOT NULL,
password VARCHAR ( 50 ) NOT NULL,
email VARCHAR ( 255 ) UNIQUE NOT NULL,
created_on TIMESTAMP NOT NULL,
allow BOOLEAN NOT NULL
);
Following is my models.py
class AccountsInfo(Base):
__tablename__ = "user_account"
user_id = Column(Integer, primary_key=True, index=True)
user_name = Column(String)
password = Column(String)
email = Column(String)
created_on = Column(DateTime)
allow = Column(Boolean)
Following is my schema.py
class AccountsInfoBase(BaseModel):
user_name: str
password: str
email: str
created_on: str
allow: bool
class Config:
orm_mode = True
class AccountsCreate(AccountsInfoBase):
password = str
class AccountsInfo(AccountsInfoBase):
user_id: int
class Config:
orm_mode = True
I use the following code to create an user,
def create_user(db: Session, user: schemas.AccountsCreate):
db_user = models.AccountsInfo(user_name=user.user_name, password=user.password, email=user.email,created_on=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),allow=True)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
The problem is that I'm getting the following error,
raise ValidationError(errors, field.type_) pydantic.error_wrappers.ValidationError: 1 validation error for AccountsInfo response -> created_on str type expected (type=type_error.str)
what am I missing?
Upvotes: 3
Views: 2463
Reputation: 20598
raise ValidationError(errors, field.type_) pydantic.error_wrappers.ValidationError: 1 validation error for AccountsInfo response -> created_on str type expected (type=type_error.str)
In your table the created_on is DateTime.
class AccountsInfo(Base):
__tablename__ = "user_account"
created_on = Column(DateTime)
But you declared as str
in your Pydantic model.
class AccountsInfoBase(BaseModel):
created_on: str
Declare your field as datetime in Pydantic model. Also SQLAlchemy gives you ability to create datetime automatically.
from sqlalchemy.sql import func
time_created = Column(DateTime(timezone=True), server_default=func.now())
Upvotes: 4