Bishwas-py / djapy

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

Add `validation_info` and `context` in `@computed_field` within `SourceAble` #19

Closed Bishwas-py closed 4 months ago

Bishwas-py commented 4 months ago

Basically getting context in @computed_field is not doable right now, if the condition is similar to below:

class AssignLikeSchema(SourceAble):

    @computed_field
    def assign_likes(self) -> SimpleLikeSchema:
        likes = PolymorphicLike.get_object_likes(self._source_obj).alive()
        return {
            'like_count': likes.count(),
            'have_self': likes.filter(user=self._context['request'].user).exists() if self._context[
                'request'].user.is_authenticated else False,
            'last_like': likes.last() if likes.exists() else None,
        }

this can be achieved with:

class SourceAble(BaseModel):
    """
    Allows the model to have a source object.
    """
    _source_obj: Any | None = None
    _validation_info: ValidationInfo | None = None
    _context: dict | None = None

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

        return obj