Я определил Enum, AccountingType, чтобы представить возможные типы учета:
Код: Выделить всё
from enum import Enum
class AccountingType(Enum):
ASSET = "Asset"
LIABILITY = "Liability"
UNKNOWN = "Unknown"
Код: Выделить всё
# Account fields ...
@property
def accounting_type(self) -> AccountingType:
"""Return the accounting type for this account based on the account sub type."""
if self.account_sub_type in constants.LIABILITY_SUB_TYPES:
return AccountingType.LIABILITY
if self.account_sub_type in constants.ASSET_SUB_TYPES:
return AccountingType.ASSET
return AccountingType.UNKNOWN
Код: Выделить всё
account = Account.objects.get(id=some_id)
if account.accounting_type == AccountingType.LIABILITY:
print("This account is a liability.")
Код: Выделить всё
class AccountDetailSerializer(serializers.ModelSerializer):
accounting_type = serializers.ReadOnlyField()
class Meta:
model = Account
fields = ['accounting_type', 'account_id', ...]
Код: Выделить всё
class AccountDetailSerializer(serializers.ModelSerializer):
accounting_type = serializers.SerializerMethodField()
class Meta:
model = Account
fields = ['accounting_type', 'account_id', ...]
def get_accounting_type(self, obj):
return obj.accounting_type.value # Return the Enum value as a string
- Есть ли причина, по которой сериализаторы.ReadOnlyField() не работают работать с @property, когда он возвращает Enum? Обрабатывает ли DRF поля @property по-разному в зависимости от типа возвращаемого значения?
- Является ли SerializerMethodField рекомендуемым подходом, когда свойство возвращает сложный тип, например Enum, требующий специальной сериализации?
Существуют ли передовые методы представления значений Enum через свойства модели в DRF?
Подробнее здесь: https://stackoverflow.com/questions/791 ... for-drf-se