posts = Post.objects.all().alive() is passed via the system to be parsed with List[PostSchema]. How can I achieve the access of ORM passed object, as mentioned below?
# Schema is slightly extended version of BaseModel
class PostSchema(Schema, ):
id: int
created_at: datetime
updated_at: datetime
soft_deleted_at: datetime | None = None
id: int
title: str
slug: str
body: str
tags: list[TagsSchema]
comments: SimpleCommentSchema
@field_validator("comments", mode="before")
def get_comments(cls, v, info, obj): # obj is the each-object passed via List[PostSchema]
comments = PolymorphicComments.objects.filter(
parent_id=obj.id,
parent_type=ContentType.objects.get_for_model(obj)).alive()
return {
'comment_count': comments.count(),
'last_comment': comments.last() if comments.exists() else None,
}
return {
'comment_count': 0,
'last_comment': None
}
The post object by ORM does not have a comments attribute, it must be a later calculated filled.