From fb1b383962cbd0c61d66bcf681f717156591a238 Mon Sep 17 00:00:00 2001 From: Sera Pikalov Date: Sun, 7 Dec 2025 12:33:54 +0200 Subject: [PATCH] fix: handle null category in TransactionCategoryField serialization Fix AttributeError when serializing transactions with null categories. The to_representation method now checks for None before accessing category properties, returning None instead of crashing. Fixes issue where API returns 500 error when retrieving transactions without assigned categories. --- app/apps/api/fields/transactions.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/apps/api/fields/transactions.py b/app/apps/api/fields/transactions.py index e4ab075..b64ac83 100644 --- a/app/apps/api/fields/transactions.py +++ b/app/apps/api/fields/transactions.py @@ -10,15 +10,19 @@ from apps.transactions.models import ( @extend_schema_field( { - "oneOf": [{"type": "string"}, {"type": "integer"}], - "description": "TransactionCategory ID or name. If the name doesn't exist, a new one will be created", + "oneOf": [{"type": "string"}, {"type": "integer"}, {"type": "null"}], + "description": "TransactionCategory ID or name. If the name doesn't exist, a new one will be created. Can be null if no category is assigned.", } ) class TransactionCategoryField(serializers.Field): def to_representation(self, value): + if value is None: + return None return {"id": value.id, "name": value.name} def to_internal_value(self, data): + if data is None: + return None if isinstance(data, int): try: return TransactionCategory.objects.get(pk=data)