| 1 |
import datetime |
| 2 |
import decimal |
| 3 |
import uuid |
| 4 |
|
| 5 |
from rest_framework import serializers |
| 6 |
|
| 7 |
|
| 8 |
class Unknown(object): |
| 9 |
pass |
| 10 |
|
| 11 |
|
| 12 |
class MethodFieldExampleSerializer(serializers.Serializer): |
| 13 |
""" |
| 14 |
Implementation of SerializerMethodField using type hinting for Python >= 3.5 |
| 15 |
""" |
| 16 |
|
| 17 |
hinted_bool = serializers.SerializerMethodField( |
| 18 |
help_text="the type hint on the method should determine this to be a bool" |
| 19 |
) |
| 20 |
|
| 21 |
def get_hinted_bool(self, obj) -> bool: |
| 22 |
return True |
| 23 |
|
| 24 |
hinted_int = serializers.SerializerMethodField( |
| 25 |
help_text="the type hint on the method should determine this to be an integer" |
| 26 |
) |
| 27 |
|
| 28 |
def get_hinted_int(self, obj) -> int: |
| 29 |
return 1 |
| 30 |
|
| 31 |
hinted_float = serializers.SerializerMethodField( |
| 32 |
help_text="the type hint on the method should determine this to be a number" |
| 33 |
) |
| 34 |
|
| 35 |
def get_hinted_float(self, obj) -> float: |
| 36 |
return 1.0 |
| 37 |
|
| 38 |
hinted_decimal = serializers.SerializerMethodField( |
| 39 |
help_text="the type hint on the method should determine this to be a decimal" |
| 40 |
) |
| 41 |
|
| 42 |
def get_hinted_decimal(self, obj) -> decimal.Decimal: |
| 43 |
return decimal.Decimal(1) |
| 44 |
|
| 45 |
hinted_datetime = serializers.SerializerMethodField( |
| 46 |
help_text="the type hint on the method should determine this to be a datetime" |
| 47 |
) |
| 48 |
|
| 49 |
def get_hinted_datetime(self, obj) -> datetime.datetime: |
| 50 |
return datetime.datetime.now() |
| 51 |
|
| 52 |
hinted_date = serializers.SerializerMethodField( |
| 53 |
help_text="the type hint on the method should determine this to be a date" |
| 54 |
) |
| 55 |
|
| 56 |
def get_hinted_date(self, obj) -> datetime.date: |
| 57 |
return datetime.date.today() |
| 58 |
|
| 59 |
hinted_uuid = serializers.SerializerMethodField( |
| 60 |
help_text="the type hint on the method should determine this to be a uuid" |
| 61 |
) |
| 62 |
|
| 63 |
def get_hinted_uuid(self, obj) -> uuid.UUID: |
| 64 |
return uuid.uuid4() |
| 65 |
|
| 66 |
hinted_unknown = serializers.SerializerMethodField( |
| 67 |
help_text="type hint is unknown, so is expected to fallback to string" |
| 68 |
) |
| 69 |
|
| 70 |
def get_hinted_unknown(self, obj) -> Unknown: |
| 71 |
return Unknown() |
| 72 |
|
| 73 |
non_hinted_number = serializers.SerializerMethodField( |
| 74 |
help_text="No hint on the method, so this is expected to fallback to string" |
| 75 |
) |
| 76 |
|
| 77 |
def get_non_hinted_number(self, obj): |
| 78 |
return 1.0 |