Closed Bishwas-py closed 4 months ago
Basically getting context in @computed_field is not doable right now, if the condition is similar to below:
@computed_field
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
Basically getting context in
@computed_field
is not doable right now, if the condition is similar to below:this can be achieved with: