Bishwas-py / djapy

No bullshit, Django Rest API Framework
https://djapy.io
59 stars 3 forks source link

Add custom computed fields, not related to the model object #16

Closed Bishwas-py closed 4 months ago

Bishwas-py commented 4 months ago

Creation of custom data should be allowed:

If posts = Post.objects.all().alive() is passed to List[PostSchema]:

class PostSchema(Schema, ):  # , AssignLikeSchema, AssignCommentSchema):
    id: int
    updated_at: datetime
    soft_deleted_at: datetime | None = None
    id: int
    title: str
    slug: str
    body: str
    tags: list[TagsSchema]
    # comments: SimpleCommentSchema # comments is not an attribute of post object

    @computed_field
    def comments(self, obj: 'model.Post') -> SimpleCommentSchema: # currently @computed_field do not allow objects to be passed
        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
        }
Bishwas-py commented 4 months ago

Created of something like Sourceable could help.

class Sourceable(BaseModel):
      _source_obj: Any | None = None

    @model_validator(mode="wrap")
    def __validator__(cls, val: Any, next_: typing.Callable[[Any], typing.Self]) -> typing.Self:
        obj = next_(val)
        obj._source_obj = val

        return obj