2
\$\begingroup\$

What does my code do? I use Django and in the following snippet, I use a class together with a TemplateView to render an HTML page. I already tried to simplify it with methods, but my code still looks "messy" and unstructured. Do you have any more recommendations on how I could make it more clear?

class Index(LoginRequiredMixin, TemplateView):
    template_name = 'admin/dashboard/index.html'

    def dispatch(self, *args, **kwargs):
        self.analytics = EventAnalytics(self.organizers)
        return super().dispatch(*args, **kwargs)

    @cached_property
    def organizers(self):
        return self.request.user.organizers.prefetch_related('events', 'events__banner')

    def group_events(self, events):
        """Group events by status."""
        grouped_events = defaultdict(list)

        for event in events:
            if event.is_archived():
                events = grouped_events[EventStatus.ARCHIVED]
            elif event.is_draft():
                events = grouped_events[EventStatus.DRAFT]
            elif event.is_over:
                events = grouped_events["past"]
            else:
                events = grouped_events[EventStatus.LIVE]

            events.append(event)

        return grouped_events

    def get_forecast_context(self, forecast_data, event):
        event_forecast = forecast_data.get(event.pk)
        if not event_forecast:
            return

        return {
            'created': event_forecast.get('created'),
            'yhat': event_forecast.get('yhat'),
            'img_key': event_forecast.get('img_key'),
        }

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['organizers'] = self.organizers
        forecast_data = self.analytics.get_forecast_data()

        event_data_by_organizer = {}
        for organizer in self.organizers:
            """
            <EventQuerySet [{'pk': 6, 'sold_tickets': 527}, {'pk': 4, 'sold_tickets': 580}, {'pk': 5, 'sold_tickets': 379}]>
            """

            event_data_by_organizer[organizer.pk] = self.analytics.event_ticket_stats(
                organizer
            )

            events = organizer.events.all()
            for event in events:
                event_data = event_data_by_organizer[organizer.pk][event.pk]
                tickets_left = (
                    event_data['available_tickets'] - event_data['sold_tickets']
                )
                days_to_event, is_event_today = self.analytics.days_to_event(event)
                avg_sales_gross_last_7_days = self.analytics.avg_sales_gross_last_7_days(
                    event
                )
                avg_sales_per_day_to_sell_out = self.analytics.avg_sales_per_day_to_sell_out(
                    event, days_to_event
                )
                forecast_context = self.get_forecast_context(forecast_data, event)

                event_data.update(
                    {
                        'days_to_event': days_to_event,
                        'show_days_to_event': max(days_to_event, 1),
                        'today': is_event_today,
                        'sales_gross_today': self.analytics.sales_gross_today(event),
                        'sales_gross_yesterday': self.analytics.sales_gross_yesterday(
                            event
                        ),
                        'tickets_left': tickets_left,
                        'avg_sales_gross_last_7_days': avg_sales_gross_last_7_days,
                        'avg_sales_per_day_to_sell_out': avg_sales_per_day_to_sell_out,
                        'forecast_context': forecast_context,
                    }
                )

            grouped_events = self.group_events(events)
            event_data_by_organizer[organizer.pk][
                'events_archived'
            ] = grouped_events.get(EventStatus.ARCHIVED)
            event_data_by_organizer[organizer.pk]['events_draft'] = grouped_events.get(
                EventStatus.DRAFT
            )
            event_data_by_organizer[organizer.pk]['events_past'] = grouped_events.get(
                'past'
            )
            event_data_by_organizer[organizer.pk]['events_live'] = grouped_events.get(
                EventStatus.LIVE
            )

        context['event_data_by_organizer'] = event_data_by_organizer

        return context
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.