from rest_framework import routers, viewsets, serializers from tickets.models import IssueThread, Comment, StateChange class IssueSerializer(serializers.ModelSerializer): timeline = serializers.SerializerMethodField() class Meta: model = IssueThread fields = ('id', 'timeline') read_only_fields = ('id', 'timeline') @staticmethod def get_timeline(obj): timeline = [] for comment in obj.comments.all(): timeline.append({ 'type': 'comment', 'id': comment.id, 'timestamp': comment.timestamp, 'comment': comment.comment, }) for state_change in obj.state_changes.all(): timeline.append({ 'type': 'state', 'id': state_change.id, 'timestamp': state_change.timestamp, 'state': state_change.state, }) for email in obj.emails.all(): timeline.append({ 'type': 'mail', 'id': email.id, 'timestamp': email.timestamp, 'sender': email.sender, 'recipient': email.recipient, 'subject': email.subject, 'body': email.body, }) return sorted(timeline, key=lambda x: x['timestamp']) class IssueViewSet(viewsets.ModelViewSet): serializer_class = IssueSerializer queryset = IssueThread.objects.all() permission_classes = [] authentication_classes = [] router = routers.SimpleRouter() router.register(r'tickets', IssueViewSet, basename='issues') urlpatterns = router.urls