uchill/backend/apps/users/mixins.py

54 lines
2.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Миксины для работы с пользователями.
"""
from rest_framework import serializers
from .utils import format_datetime_for_user
class TimezoneAwareSerializerMixin:
"""
Миксин для автоматической конвертации datetime полей в часовой пояс пользователя.
Использование:
class MySerializer(TimezoneAwareSerializerMixin, serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ['id', 'created_at', 'updated_at', ...]
Автоматически конвертирует все datetime поля в часовой пояс пользователя из request.user.timezone
"""
def to_representation(self, instance):
"""Переопределяем для конвертации времени в часовой пояс пользователя."""
data = super().to_representation(instance)
# Получаем часовой пояс пользователя из request
request = self.context.get('request')
user_timezone = 'UTC'
if request and hasattr(request, 'user') and request.user.is_authenticated:
user_timezone = request.user.timezone or 'UTC'
# Список полей для конвертации (можно переопределить в дочерних классах)
datetime_fields = getattr(self.Meta, 'timezone_aware_fields', None)
if datetime_fields is None:
# Автоматически определяем datetime поля из модели
if hasattr(self.Meta, 'model'):
model = self.Meta.model
datetime_fields = []
for field in model._meta.get_fields():
if hasattr(field, 'get_internal_type'):
field_type = field.get_internal_type()
if field_type in ['DateTimeField', 'DateField']:
datetime_fields.append(field.name)
# Конвертируем все datetime поля в часовой пояс пользователя
if datetime_fields:
for field_name in datetime_fields:
if field_name in data and data[field_name]:
field_value = getattr(instance, field_name, None)
if field_value:
data[field_name] = format_datetime_for_user(field_value, user_timezone)
return data