42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
```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(BaseModel):
|
|
title: Optional[str] = None
|
|
content: Optional[str] = None
|
|
|
|
class PostInDBBase(PostBase):
|
|
id: int
|
|
created_at: datetime
|
|
updated_at: Optional[datetime] = None
|
|
|
|
class Config:
|
|
orm_mode = True
|
|
|
|
class Post(PostInDBBase):
|
|
pass
|
|
|
|
class PostInDB(PostInDBBase):
|
|
pass
|
|
```
|
|
|
|
Explanation:
|
|
|
|
1. We import the necessary modules: `typing` for type hints, `pydantic` for defining data models, and `datetime` for working with date and time.
|
|
|
|
|
|
3. `PostCreate` inherits from `PostBase` and is used for creating a new post.
|
|
|
|
|
|
5. `PostInDBBase` inherits from `PostBase` and adds fields specific to the database representation: `id`, `created_at`, and `updated_at`. The `Config` class is used to enable the ORM mode, which allows Pydantic to work with SQLAlchemy models.
|
|
|
|
6. `Post` and `PostInDB` are response schemas that inherit from `PostInDBBase`. These schemas will be used to serialize the data returned from the API. |