2021-08-25 11:02:50 +00:00
|
|
|
import json
|
2022-06-23 05:52:28 +00:00
|
|
|
import logging
|
2023-04-18 10:56:17 +00:00
|
|
|
import uuid
|
2022-06-23 05:52:28 +00:00
|
|
|
from datetime import datetime
|
2021-08-25 11:02:50 +00:00
|
|
|
|
|
|
|
from django.conf import settings
|
2023-04-18 10:56:17 +00:00
|
|
|
from django.db import models
|
|
|
|
from django.utils import timezone as dj_timezone
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2021-08-25 11:02:50 +00:00
|
|
|
|
2023-07-24 03:52:25 +00:00
|
|
|
lazy_type = type(_('gettext_lazy'))
|
2022-06-23 05:52:28 +00:00
|
|
|
|
2021-08-25 11:02:50 +00:00
|
|
|
|
|
|
|
class ModelJSONFieldEncoder(json.JSONEncoder):
|
|
|
|
""" 解决一些类型的字段不能序列化的问题 """
|
|
|
|
|
|
|
|
def default(self, obj):
|
2022-06-23 05:52:28 +00:00
|
|
|
str_cls = (models.Model, lazy_type, models.ImageField, uuid.UUID)
|
|
|
|
if isinstance(obj, str_cls):
|
2021-08-25 11:02:50 +00:00
|
|
|
return str(obj)
|
2022-06-23 05:52:28 +00:00
|
|
|
elif isinstance(obj, datetime):
|
2022-07-12 07:28:42 +00:00
|
|
|
obj = dj_timezone.localtime(obj)
|
2022-06-23 05:52:28 +00:00
|
|
|
return obj.strftime(settings.DATETIME_DISPLAY_FORMAT)
|
|
|
|
elif isinstance(obj, (list, tuple)) and len(obj) > 0 \
|
|
|
|
and isinstance(obj[0], models.Model):
|
|
|
|
return [str(i) for i in obj]
|
2021-08-25 11:02:50 +00:00
|
|
|
else:
|
2022-06-23 05:52:28 +00:00
|
|
|
try:
|
|
|
|
return super().default(obj)
|
|
|
|
except TypeError:
|
2023-04-18 10:56:17 +00:00
|
|
|
logging.error(f'Type error: {type(obj)}')
|
2022-06-23 05:52:28 +00:00
|
|
|
return str(obj)
|