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.