Python django.db.models.Sum() Examples

The following are 30 code examples for showing how to use django.db.models.Sum(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: trader   Author: BigBrotherTrade   File: brother2.py    License: Apache License 2.0 6 votes vote down vote up
def update_equity(self):
        today, trading = await is_trading_day(datetime.datetime.today().replace(tzinfo=pytz.FixedOffset(480)))
        if trading:
            logger.info('更新资金净值 %s %s', today, trading)
            dividend = Performance.objects.filter(
                broker=self.__broker, day__lt=today.date()).aggregate(Sum('dividend'))['dividend__sum']
            if dividend is None:
                dividend = Decimal(0)
            perform = Performance.objects.filter(
                broker=self.__broker, day__lt=today.date()).order_by('-day').first()
            if perform is None:
                unit = Decimal(1000000)
            else:
                unit = perform.unit_count
            nav = self.__current / unit
            accumulated = (self.__current - dividend) / (unit - dividend)
            Performance.objects.update_or_create(broker=self.__broker, day=today.date(), defaults={
                'used_margin': self.__margin,
                'capital': self.__current, 'unit_count': unit, 'NAV': nav, 'accumulated': accumulated}) 
Example 2
Project: django-accounting   Author: dulacp   File: views.py    License: MIT License 6 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        user = self.request.user
        orgas = organization_manager.get_user_organizations(user)
        cumulated_turnovers = (orgas
            .aggregate(sum=Sum('invoices__total_excl_tax'))["sum"]) or D('0')
        cumulated_debts = (orgas
            .aggregate(sum=Sum('bills__total_excl_tax'))["sum"]) or D('0')
        cumulated_profits = cumulated_turnovers - cumulated_debts

        context["organizations_count"] = orgas.count()
        context["organizations_cumulated_turnovers"] = cumulated_turnovers
        context["organizations_cumulated_profits"] = cumulated_profits
        context["organizations_cumulated_active_days"] = 0

        context["organizations"] = orgas
        context["last_invoices"] = Invoice.objects.all()[:10]

        return context 
Example 3
Project: donation-tracker   Author: GamesDoneQuick   File: public.py    License: Apache License 2.0 6 votes vote down vote up
def runindex(request, event=None):
    event = viewutil.get_event(event)

    if not event.id:
        return HttpResponseRedirect(
            reverse('tracker:runindex', args=(Event.objects.latest().short,))
        )

    searchParams = {}
    searchParams['event'] = event.id

    runs = filters.run_model_query('run', searchParams)
    runs = runs.annotate(hasbids=Sum('bids'))

    return views_common.tracker_response(
        request, 'tracker/runindex.html', {'runs': runs, 'event': event},
    ) 
Example 4
Project: donation-tracker   Author: GamesDoneQuick   File: bid.py    License: Apache License 2.0 6 votes vote down vote up
def update_total(self):
        if self.istarget:
            self.total = self.bids.filter(
                donation__transactionstate='COMPLETED'
            ).aggregate(Sum('amount'))['amount__sum'] or Decimal('0.00')
            self.count = self.bids.filter(
                donation__transactionstate='COMPLETED'
            ).count()
            # auto close this if it's a challenge with no children and the goal's been met
            if (
                self.goal
                and self.state == 'OPENED'
                and self.total >= self.goal
                and self.istarget
            ):
                self.state = 'CLOSED'
        else:
            options = self.options.exclude(
                state__in=('HIDDEN', 'DENIED', 'PENDING')
            ).aggregate(Sum('total'), Sum('count'))
            self.total = options['total__sum'] or Decimal('0.00')
            self.count = options['count__sum'] or 0 
Example 5
Project: contratospr-api   Author: Code4PuertoRico   File: viewsets.py    License: Apache License 2.0 6 votes vote down vote up
def spending_over_time(self, request):
        fiscal_year = request.query_params.get("fiscal_year")

        queryset = self.filter_queryset(self.get_queryset())

        if fiscal_year:
            start_date, end_date = get_fiscal_year_range(int(fiscal_year))
            queryset = queryset.filter(
                date_of_grant__gte=start_date, date_of_grant__lte=end_date
            )

        queryset = (
            queryset.without_amendments()
            .annotate(month=TruncMonth("date_of_grant"))
            .values("month")
            .annotate(total=Sum("amount_to_pay"), count=Count("id"))
            .values("month", "total", "count")
            .order_by("month")
        )

        return Response(queryset) 
Example 6
Project: contratospr-api   Author: Code4PuertoRico   File: filters.py    License: Apache License 2.0 6 votes vote down vote up
def filter_entities(self, queryset, name, value):
        if not value:
            return queryset
        return (
            queryset.filter(contract__entity__in=value)
            .distinct()
            .annotate(
                contracts_total=Sum(
                    "contract__amount_to_pay",
                    filter=Q(contract__parent=None, contract__entity__in=value),
                ),
                contracts_count=Count(
                    "contract",
                    filter=Q(contract__parent=None, contract__entity__in=value),
                ),
            )
        ) 
Example 7
Project: contratospr-api   Author: Code4PuertoRico   File: filters.py    License: Apache License 2.0 6 votes vote down vote up
def filter_entity_by_id(self, queryset, name, value):
        if not value:
            return queryset

        return (
            queryset.filter(contract__entity_id__in=value)
            .distinct()
            .annotate(
                contracts_total=Sum(
                    "contract__amount_to_pay",
                    filter=Q(contract__parent=None, contract__entity_id__in=value),
                ),
                contracts_count=Count(
                    "contract",
                    filter=Q(contract__parent=None, contract__entity_id__in=value),
                ),
            )
        ) 
Example 8
Project: contratospr-api   Author: Code4PuertoRico   File: filters.py    License: Apache License 2.0 6 votes vote down vote up
def filter_contractors_by_id(self, queryset, name, value):
        if not value:
            return queryset

        contracts = Contract.objects.filter(contractors__in=value).only("id")

        return (
            queryset.filter(contract__in=contracts)
            .distinct()
            .annotate(
                contracts_total=Sum(
                    "contract__amount_to_pay",
                    filter=Q(contract__parent=None, contract__in=contracts),
                ),
                contracts_count=Count(
                    "contract", filter=Q(contract__parent=None, contract__in=contracts)
                ),
            )
        ) 
Example 9
Project: koku   Author: project-koku   File: tests_queries.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_with_wildcard_tag_filter(self):
        """Test that data is filtered to include entries with tag key."""
        url = "?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly"  # noqa: E501
        query_params = self.mocked_query_params(url, AWSTagView)
        handler = AWSTagQueryHandler(query_params)
        tag_keys = handler.get_tag_keys()
        filter_key = tag_keys[0]
        tag_keys = ["tag:" + tag for tag in tag_keys]

        with tenant_context(self.tenant):
            totals = AWSCostEntryLineItemDailySummary.objects.filter(
                usage_start__gte=self.dh.this_month_start
            ).aggregate(**{"cost": Sum(F("unblended_cost") + F("markup_cost"))})

        url = f"?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly&filter[tag:{filter_key}]=*"  # noqa: E501
        query_params = self.mocked_query_params(url, AWSCostView)
        handler = AWSReportQueryHandler(query_params)
        data = handler.execute_query()
        data_totals = data.get("total", {})
        result = data_totals.get("cost", {}).get("total", {}).get("value")
        self.assertEqual(result, totals["cost"]) 
Example 10
Project: koku   Author: project-koku   File: tests_azure_query_handler.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_with_wildcard_tag_filter(self):
        """Test that data is filtered to include entries with tag key."""
        # Pick tags for the same month we query on later
        url = "?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly"
        query_params = self.mocked_query_params(url, AzureTagView)
        handler = AzureTagQueryHandler(query_params)
        tag_keys = handler.get_tag_keys()
        filter_key = tag_keys[0]
        tag_keys = ["tag:" + tag for tag in tag_keys]

        ag_key = "cost_total"
        with tenant_context(self.tenant):
            totals = AzureCostEntryLineItemDailySummary.objects.filter(
                usage_start__gte=self.dh.this_month_start
            ).aggregate(**{ag_key: Sum(F("pretax_cost") + F("markup_cost"))})

        url = f"?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly&filter[tag:{filter_key}]=*"  # noqa: E501
        query_params = self.mocked_query_params(url, AzureCostView)
        handler = AzureReportQueryHandler(query_params)

        data = handler.execute_query()
        data_totals = data.get("total", {})
        result = data_totals.get("cost", {}).get("total")
        self.assertIsNotNone(result)
        self.assertAlmostEqual(result.get("value"), totals[ag_key], 6) 
Example 11
Project: koku   Author: project-koku   File: test_azure_report_db_accessor.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_populate_markup_cost_no_billsids(self):
        """Test that the daily summary table is populated."""
        summary_table_name = AZURE_REPORT_TABLE_MAP["line_item_daily_summary"]
        summary_table = getattr(self.accessor.report_schema, summary_table_name)

        query = self.accessor._get_db_obj_query(summary_table_name)
        with schema_context(self.schema):
            expected_markup = query.aggregate(markup=Sum(F("pretax_cost") * decimal.Decimal(0.1)))
            expected_markup = expected_markup.get("markup")
            summary_entry = summary_table.objects.all().aggregate(Min("usage_start"), Max("usage_start"))
            start_date = summary_entry["usage_start__min"]
            end_date = summary_entry["usage_start__max"]

        self.accessor.populate_markup_cost(0.1, start_date, end_date, None)
        with schema_context(self.schema):
            query = self.accessor._get_db_obj_query(summary_table_name).aggregate(Sum("markup_cost"))
            actual_markup = query.get("markup_cost__sum")
            self.assertAlmostEqual(actual_markup, expected_markup, 6) 
Example 12
Project: koku   Author: project-koku   File: test_aws_report_db_accessor.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_populate_markup_cost_no_billsids(self):
        """Test that the daily summary table is populated."""
        summary_table_name = AWS_CUR_TABLE_MAP["line_item_daily_summary"]
        summary_table = getattr(self.accessor.report_schema, summary_table_name)

        query = self.accessor._get_db_obj_query(summary_table_name)
        with schema_context(self.schema):
            expected_markup = query.aggregate(markup=Sum(F("unblended_cost") * decimal.Decimal(0.1)))
            expected_markup = expected_markup.get("markup")

            summary_entry = summary_table.objects.all().aggregate(Min("usage_start"), Max("usage_start"))
            start_date = summary_entry["usage_start__min"]
            end_date = summary_entry["usage_start__max"]

        self.accessor.populate_markup_cost(0.1, start_date, end_date, None)
        with schema_context(self.schema):
            query = self.accessor._get_db_obj_query(summary_table_name).aggregate(Sum("markup_cost"))
            actual_markup = query.get("markup_cost__sum")
            self.assertAlmostEqual(actual_markup, expected_markup, 6) 
Example 13
Project: timed-backend   Author: adfinis-sygroup   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def calculate_credit(self, user, start, end):
        """
        Calculate approved days of type for user in given time frame.

        For absence types which fill worktime this will be None.
        """
        if self.fill_worktime:
            return None

        credits = AbsenceCredit.objects.filter(
            user=user, absence_type=self, date__range=[start, end]
        )
        data = credits.aggregate(credit=Sum("days"))
        credit = data["credit"] or 0

        return credit 
Example 14
Project: silverstrike   Author: agstrike   File: reports.py    License: MIT License 6 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(IncomeExpenseReport, self).get_context_data(**kwargs)
        queryset = Split.objects.past().order_by()
        incomes = queryset.income().annotate(m=TruncMonth('date')).values('m').annotate(
            total=models.Sum('amount'))
        expenses = queryset.expense().annotate(m=TruncMonth('date')).values('m').annotate(
            total=models.Sum('amount'))
        result = []
        for i, e in zip(incomes, expenses):
            result.append({
                'month': i['m'],
                'income': i['total'],
                'expense': e['total'],
                'total': i['total'] + e['total']
            })
        context['result'] = result
        return context 
Example 15
Project: silverstrike   Author: agstrike   File: api.py    License: MIT License 6 votes vote down vote up
def get_balances(request, dstart, dend):
    try:
        dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d').date()
        dend = datetime.datetime.strptime(dend, '%Y-%m-%d').date()
    except ValueError:
        return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd'))
    balance = Split.objects.personal().exclude_transfers().filter(date__lt=dstart).aggregate(
            models.Sum('amount'))['amount__sum'] or 0
    splits = Split.objects.personal().exclude_transfers().date_range(dstart, dend).order_by('date')
    data_points = []
    labels = []
    days = (dend - dstart).days
    if days > 50:
        step = days / 50 + 1
    else:
        step = 1
    for split in splits:
        while split.date > dstart:
            data_points.append(balance)
            labels.append(datetime.datetime.strftime(dstart, '%Y-%m-%d'))
            dstart += datetime.timedelta(days=step)
        balance += split.amount
    data_points.append(balance)
    labels.append(datetime.datetime.strftime(dend, '%Y-%m-%d'))
    return JsonResponse({'labels': labels, 'data': data_points}) 
Example 16
Project: silverstrike   Author: agstrike   File: test_forms.py    License: MIT License 6 votes vote down vote up
def test_TransferForm(self):
        data = {
            'title': 'transfer',
            'src': self.account.pk,
            'dst': self.personal.pk,
            'amount': 123,
            'date': '2017-01-01'
            }
        form = TransferForm(data)
        self.assertTrue(form.is_valid())
        transfer = form.save()
        self.assertIsInstance(transfer, Transaction)
        self.assertEqual(len(Account.objects.all()), 3)  # System account is also present
        self.assertEqual(len(Transaction.objects.all()), 1)
        self.assertEqual(len(Split.objects.all()), 2)
        self.assertEqual(Split.objects.all().aggregate(
            models.Sum('amount'))['amount__sum'], 0)
        self.assertTrue(Split.objects.get(
            account=self.personal, opposing_account=self.account, amount=123).is_transfer)
        self.assertTrue(Split.objects.get(
            account=self.account, opposing_account=self.personal, amount=-123).is_transfer) 
Example 17
Project: Servo   Author: fpsw   File: invoices.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_payment_total(self):
        from django.db.models import Sum
        result = self.payment_set.all().aggregate(Sum('amount'))
        return result['amount__sum'] 
Example 18
Project: Servo   Author: fpsw   File: calendar.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_total_hours(self, start=None, finish=None):
        """
        Returns in hours, the total duration of events in this calendar within
        a time period.
        """
        events = self.calendarevent_set.all()

        if start and finish:
            events = self.calendarevent_set.filter(started_at__range=(start, finish))

        total = events.aggregate(total=Sum('seconds'))['total'] or 0

        return math.ceil(total/3600.0) 
Example 19
Project: booking-example   Author: andreagrandi   File: booking.py    License: MIT License 5 votes vote down vote up
def get_expected_diners(restaurant, booking_date):
    """
    Return the expected number of diners of a restaurant for a specific date.
    """
    diners = Booking.objects.filter(
        table__restaurant=restaurant,
        booking_date_time_start__year=booking_date.year,
        booking_date_time_start__month=booking_date.month,
        booking_date_time_start__day=booking_date.day).aggregate(Sum('people'))
    return diners['people__sum'] 
Example 20
Project: django-accounting   Author: dulacp   File: managers.py    License: MIT License 5 votes vote down vote up
def _get_total(self, prop):
        return self.aggregate(sum=Sum(prop))["sum"] 
Example 21
Project: donation-tracker   Author: GamesDoneQuick   File: public.py    License: Apache License 2.0 5 votes vote down vote up
def index(request, event=None):
    event = viewutil.get_event(event)
    eventParams = {}

    if event.id:
        eventParams['event'] = event.id

    agg = Donation.objects.filter(
        transactionstate='COMPLETED', testdonation=False, **eventParams
    ).aggregate(
        amount=Cast(Coalesce(Sum('amount'), 0), output_field=FloatField()),
        count=Count('amount'),
        max=Cast(Coalesce(Max('amount'), 0), output_field=FloatField()),
        avg=Cast(Coalesce(Avg('amount'), 0), output_field=FloatField()),
    )
    agg['target'] = float(event.targetamount)
    count = {
        'runs': filters.run_model_query('run', eventParams).count(),
        'prizes': filters.run_model_query('prize', eventParams).count(),
        'bids': filters.run_model_query('bid', eventParams).count(),
        'donors': filters.run_model_query('donorcache', eventParams)
        .values('donor')
        .distinct()
        .count(),
    }

    if 'json' in request.GET:
        return HttpResponse(
            json.dumps({'count': count, 'agg': agg}, ensure_ascii=False,),
            content_type='application/json;charset=utf-8',
        )

    return views_common.tracker_response(
        request, 'tracker/index.html', {'agg': agg, 'count': count, 'event': event}
    ) 
Example 22
Project: donation-tracker   Author: GamesDoneQuick   File: event.py    License: Apache License 2.0 5 votes vote down vote up
def donor_report(self, request, queryset):
        if queryset.count() != 1:
            self.message_user(
                request, 'Select exactly one event.', level=messages.ERROR,
            )
            return
        event = queryset.first()
        response = HttpResponse(content_type='text/csv; charset=utf-8')
        response['Content-Disposition'] = (
            'attachment; filename="donor-report-%s.csv"' % event.short
        )
        writer = csv.writer(response)
        writer.writerow(['Name', 'Donation Sum', 'Donation Count'])
        anon = tracker.models.Donation.objects.filter(
            donor__visibility='ANON', transactionstate='COMPLETED', event=event
        )
        writer.writerow(
            [
                'All Anonymous Donations',
                anon.aggregate(Sum('amount'))['amount__sum'].quantize(Decimal('1.00')),
                anon.count(),
            ]
        )
        donors = (
            tracker.models.DonorCache.objects.filter(event=event)
            .exclude(donor__visibility='ANON')
            .select_related('donor')
            .iterator()
        )
        for d in donors:
            writer.writerow([d.visible_name(), d.donation_total, d.donation_count])
        return response 
Example 23
Project: donation-tracker   Author: GamesDoneQuick   File: event.py    License: Apache License 2.0 5 votes vote down vote up
def email_report(self, request, queryset):
        if queryset.count() != 1:
            self.message_user(
                request, 'Select exactly one event.', level=messages.ERROR,
            )
            return
        event = queryset.first()
        response = HttpResponse(content_type='text/csv; charset=utf-8')
        response['Content-Disposition'] = (
            'attachment; filename="email-report-%s.csv"' % event.short
        )
        writer = csv.writer(response)
        writer.writerow(['Email', 'Name', 'Anonymous', 'Donation Sum', 'Country'])
        donors = (
            tracker.models.DonorCache.objects.filter(
                event=event, donor__solicitemail='OPTIN',
            )
            .select_related('donor')
            .iterator()
        )
        for d in donors:
            if d.firstname:
                if d.lastname:
                    name = u'%s, %s' % (d.lastname, d.firstname)
                else:
                    name = d.firstname
            else:
                name = '(No Name Supplied)'
            writer.writerow(
                [
                    d.email,
                    name,
                    d.visibility == 'ANON',
                    d.donation_total,
                    d.addresscountry,
                ]
            )
        return response 
Example 24
Project: donation-tracker   Author: GamesDoneQuick   File: prize.py    License: Apache License 2.0 5 votes vote down vote up
def current_win_count(self):
        return sum(
            [
                x
                for x in list(
                    self.get_prize_winners()
                    .aggregate(Sum('pendingcount'), Sum('acceptcount'))
                    .values()
                )
                if x is not None
            ]
        ) 
Example 25
Project: donation-tracker   Author: GamesDoneQuick   File: prize.py    License: Apache License 2.0 5 votes vote down vote up
def clean(self):
        self.sumcount = self.pendingcount + self.acceptcount + self.declinecount
        if self.sumcount == 0:
            raise ValidationError('Sum of counts must be greater than zero')
        if self.sumcount > self.prize.maxmultiwin:
            raise ValidationError(
                'Sum of counts must be at most the prize multi-win multiplicity'
            )
        prizeSum = self.acceptcount + self.pendingcount
        for winner in self.prize.prizewinner_set.exclude(pk=self.pk):
            prizeSum += winner.acceptcount + winner.pendingcount
        if prizeSum > self.prize.maxwinners:
            raise ValidationError(
                'Number of prize winners is greater than the maximum for this prize.'
            )
        if self.trackingnumber and not self.couriername:
            raise ValidationError(
                'A tracking number is only useful with a courier name as well!'
            )
        if self.winner and self.acceptcount > 0 and self.prize.requiresshipping:
            if not self.prize.is_country_region_allowed(
                self.winner.addresscountry, self.winner.addressstate
            ):
                message = 'Unfortunately, for legal or logistical reasons, we cannot ship this prize to that region. Please accept our deepest apologies.'
                coordinator = self.prize.event.prizecoordinator
                if coordinator:
                    message += ' If you have any questions, please contact our prize coordinator at {0}'.format(
                        coordinator.email
                    )
                raise ValidationError(message)
        if self.prize.key_code and not hasattr(self, 'prize_key'):
            raise ValidationError(
                'Prize winners attached to key code prizes need a prize key attached as well.'
            ) 
Example 26
Project: donation-tracker   Author: GamesDoneQuick   File: donation.py    License: Apache License 2.0 5 votes vote down vote up
def update(self):
        aggregate = Donation.objects.filter(
            donor=self.donor, transactionstate='COMPLETED'
        )
        if self.event:
            aggregate = aggregate.filter(event=self.event)
        aggregate = aggregate.aggregate(
            total=Coalesce(Sum('amount'), 0.0),
            count=Coalesce(Count('amount'), 0),
            max=Coalesce(Max('amount'), 0.0),
            avg=Coalesce(Avg('amount'), 0.0),
        )
        self.donation_total = aggregate['total']
        self.donation_count = aggregate['count']
        self.donation_max = aggregate['max']
        self.donation_avg = aggregate['avg'] 
Example 27
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def base_units_assigned(self):
        crs = TACourse.objects.filter(contract__application=self).exclude(contract__status__in=['CAN', 'REJ'])\
            .aggregate(Sum('bu'))
        return crs['bu__sum'] 
Example 28
Project: longclaw   Author: JamesRamm   File: stats.py    License: MIT License 5 votes vote down vote up
def sales_by_product(from_date, to_date):
    sales = OrderItem.objects.filter(
        Q(order__payment_date__lte=to_date) & Q(order__payment_date__gte=from_date)
    ).exclude(
        order__status=Order.CANCELLED
    ).annotate(
        title=F('product__product__title')
    ).values(
        'title'
    ).annotate(
        quantity=Sum('quantity')
    ).order_by('-quantity')

    return sales 
Example 29
Project: rcfbpoll   Author: sirgippy   File: views.py    License: BSD Zero Clause License 5 votes vote down vote up
def home(request):
    polls = Poll.objects.filter(close_date__lt=timezone.now()).order_by('-close_date')
    most_recent_poll = polls[0]

    ranks = PollCompare.objects.filter(poll=most_recent_poll).order_by('rank')
    top25 = ranks.filter(rank__lte=25)
    others = ranks.filter(rank__gt=25)
    up_movers = ranks.order_by('-ppv_diff')[0:5]
    down_movers = ranks.order_by('ppv_diff')[0:5]

    # Tally first-place votes by team
    votes = BallotEntry.objects.filter(
        ballot__poll=most_recent_poll,
        ballot__submission_date__isnull=False,
        rank=1
    ).values('team').annotate(total=Sum('rank'))
    fp_votes = {}
    for vote in votes:
        fp_votes[vote['team']] = vote['total']

    # Find which teams dropped out from last week's poll
    dropped = []
    prev_poll = most_recent_poll.last_week
    if prev_poll is not None:
        prev_top25 = PollCompare.objects.filter(poll=prev_poll, rank__lte=25).order_by('rank')

        teams = []
        for team in top25:
            teams.append(team.team.pk)

        for team in prev_top25:
            if team.team.pk not in teams:
                dropped.append(team)

    return render(request, 'poll/home.html', {'poll': most_recent_poll,
                                              'top25': top25,
                                              'others': others,
                                              'up_movers': up_movers,
                                              'down_movers': down_movers,
                                              'dropped': dropped,
                                              'fp_votes': fp_votes}) 
Example 30
Project: woid   Author: vitorfs   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def year(request, slug, year):
    service = get_object_or_404(Service, slug=slug)
    queryset = service.stories \
        .filter(status=Story.OK, date__year=year) \
        .values('url', 'title') \
        .annotate(score=Sum('score'), date=Min('date')) \
        .order_by('-score')
    return stories(request, service, queryset, year)