最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to achieve similar behaviour as DRF's get_field() with pydantic schema - Stack Overflow

programmeradmin2浏览0评论

I have three models - Nomenclature (N), NomenclaureAvailability (NA) and StatusHistory (SH). I need to monitor N quite often and record the last time it has answered. The idea was to store current status and last_answer_date of N in related NA and during serialisation i did this:

class NomenclatureSerializer(serializers.ModelSerializer):

    status = serializers.SerializerMethodField()
    last_answer = serializers.SerializerMethodField()

    ...

    def get_status(self, obj) -> int | None:
        try:
            return obj.availability.status
        except AttributeError:
            return None

    def get_last_answer(self, obj) -> str:
        try:
            return f'{obj.availability.last_answer_date:%Y-%m-%d %H:%M:%S}'
        except AttributeError:
            return 'Was never online'

The purpose of SH is literally to "log" every status change of NA. This system works well enough.

Recently i started to learn FastAPI + Pydantic + SQLAclhemy, since in DRF most of the code was already implemented before me. So i began to rewrite my project on the new framework and i don't quite understand how to achieve this SerializerMethodField() + def get_<field_name> thing in pydantic.

发布评论

评论列表(0)

  1. 暂无评论