40 lines
1.3 KiB
Python
40 lines
1.3 KiB
Python
from datetime import datetime
|
|
from typing import Optional, List, Any, ClassVar
|
|
from pydantic import BaseModel, Field, GetJsonSchemaHandler
|
|
from pydantic.json_schema import JsonSchemaValue
|
|
from bson import ObjectId
|
|
|
|
class PyObjectId(ObjectId):
|
|
@classmethod
|
|
def __get_validators__(cls):
|
|
yield cls.validate
|
|
|
|
@classmethod
|
|
def validate(cls, v, self_instance=None):
|
|
if not ObjectId.is_valid(v):
|
|
raise ValueError('Invalid ObjectId')
|
|
return ObjectId(v)
|
|
|
|
@classmethod
|
|
def __get_pydantic_json_schema__(
|
|
cls, __core_schema: Any, __field_schema: Any, __handler: GetJsonSchemaHandler
|
|
) -> JsonSchemaValue:
|
|
field_schema = __handler(__core_schema)
|
|
field_schema.update(type='string')
|
|
return field_schema
|
|
|
|
class TeamModel(BaseModel):
|
|
"""Database model for a team"""
|
|
id: Optional[PyObjectId] = Field(default_factory=PyObjectId, alias="_id")
|
|
name: str
|
|
description: Optional[str] = None
|
|
created_at: datetime = Field(default_factory=datetime.utcnow)
|
|
updated_at: Optional[datetime] = None
|
|
|
|
model_config: ClassVar[dict] = {
|
|
"populate_by_name": True,
|
|
"arbitrary_types_allowed": True,
|
|
"json_encoders": {
|
|
ObjectId: str
|
|
}
|
|
} |