4/app/api/v1/schemas/posts.py
2025-03-20 09:54:31 +01:00

41 lines
1.5 KiB
Python

Here's the `posts.py` file with the `PostsCreate` and `Posts` schemas for the `blog_app`:
```python
# app/api/v1/schemas/posts.py
from typing import Optional
from pydantic import BaseModel
from datetime import datetime
class PostsCreate(BaseModel):
title: str
content: str
published: bool = False
class Posts(BaseModel):
id: int
title: str
content: str
published: bool
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
orm_mode = True
```
Explanation:
1. The `PostsCreate` schema defines the fields required for creating a new post. It includes `title`, `content`, and an optional `published` field with a default value of `False`.
2. The `Posts` schema defines the fields for representing a post in the database. It includes `id`, `title`, `content`, `published`, `created_at`, and an optional `updated_at` field.
3. The `orm_mode = True` is set in the `Config` class of the `Posts` schema to allow Pydantic to automatically convert data from ORM objects (e.g., SQLAlchemy models) to Pydantic models and vice versa.
4. The `Optional` type from the `typing` module is used for the `updated_at` field, indicating that it can be `None`.
5. The `datetime` type is imported from the `datetime` module to represent the `created_at` and `updated_at` fields.
This file should be placed in the `app/api/v1/schemas/` directory, following the typical FastAPI project structure.
Make sure to install the required dependencies (`pydantic` and `typing`) in your project environment if they are not installed already.