from rest_framework.serializers import ModelSerializer, SerializerMethodField from room.serializers import RoomUserSerializer from .models import CustomUser class UserSerializer(ModelSerializer): room = SerializerMethodField() class Meta: model = CustomUser fields = ('email', 'last_login', 'date_joined', 'is_staff', 'username', "id_code", 'room', 'first_name', 'last_name') def get_room(self, obj): try: return RoomUserSerializer(obj.room_set.all(), many=True, context={'userId': obj.id_code}).data except: return RoomUserSerializer(obj.room_set.all(), many=True).data class UserEditSerializer(ModelSerializer): class Meta: model = CustomUser fields = ('email', 'username', 'last_name', 'first_name')