Skip to content

Commit 254239b

Browse files
committed
fix: consistently handle validation errors across functions
- Change ValueError to ValidationError for consistency in error handling - Add docstring to the get_users function to describe its purpose Signed-off-by: kyo <[email protected]>
1 parent cb2ada9 commit 254239b

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

post/schemas.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from ninja import Field, FilterSchema, Schema
55
from pydantic import model_validator
6+
from django.core.exceptions import ValidationError
67

78
from post.models import Post
89

@@ -64,7 +65,7 @@ def check_date_range(self) -> Self:
6465
return self
6566

6667
if not all([self.start_date, self.end_date]):
67-
raise ValueError('開始日期和結束日期必須同時提供或同時不提供')
68+
raise ValidationError('開始日期和結束日期必須同時提供或同時不提供')
6869

6970
# 顯式告訴 Mypy 這兩個變數在這裡是非 None 的
7071
assert self.start_date is not None
@@ -74,9 +75,9 @@ def check_date_range(self) -> Self:
7475
start_date_dt = datetime.strptime(self.start_date, '%Y-%m-%d')
7576
end_date_dt = datetime.strptime(self.end_date, '%Y-%m-%d')
7677
except ValueError:
77-
raise ValueError('日期格式無效,應為 YYYY-MM-DD')
78+
raise ValidationError('日期格式無效,應為 YYYY-MM-DD')
7879

7980
if start_date_dt > end_date_dt:
80-
raise ValueError('開始日期必須早於結束日期')
81+
raise ValidationError('開始日期必須早於結束日期')
8182

8283
return self

user/api.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111

1212
@router.get(path='/users/', response=list[str], summary='取得所有使用者')
1313
def get_users(request: HttpRequest) -> list[str]:
14+
"""
15+
取得所有使用者
16+
"""
1417
users = User.objects.all()
1518
return [user.username for user in users]
1619

0 commit comments

Comments
 (0)