42 lines
1.1 KiB
Python

from typing import Optional
from pydantic import BaseModel
from datetime import datetime
class PostBase(BaseModel):
title: str
content: str
class PostCreate(PostBase):
pass
class PostUpdate(PostBase):
pass
class PostInDBBase(PostBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
orm_mode = True
class Post(PostInDBBase):
pass
class PostList(BaseModel):
__root__: list[Post]
Explanation:
1. We import the necessary modules: `typing` for type hints, `pydantic` for defining data models, and `datetime` for handling date and time.
2. `PostBase` is a base Pydantic model that defines the common fields for a post: `title` and `content`.
5. `PostInDBBase` inherits from `PostBase` and adds additional fields: `id` (post ID), `created_at` (creation timestamp), and `updated_at` (optional update timestamp). The `Config` class is set to `orm_mode = True` to allow Pydantic to work with SQLAlchemy models.
Make sure to install the required dependencies (`pydantic` and `sqlalchemy`) in your project environment if you haven't already done so.