如何从视图访问管理员变更列表?

时间:2019-01-30 10:30:11

标签: python django django-admin

如何从视图访问过滤的表?我想将表导出到xls,但是它需要整个表,而不是经过过滤的表。在admin.py中,我可以像这样过滤查询集:

response = super(ScheduleAdmin, self).changelist_view(request, extra_context)
    qs = response.context_data["cl"].queryset

这是我的admin.py类:

class StatsScheduleAdmin(ScheduleAdmin):
list_display = (
    'get_name',
    'code',
    'get_planned_hours',
    'get_done_hours',
    #'get_planned_cost_workers',
    'get_done_cost_workers',
    #'get_planned_cost',
    'get_avg_cost',
    #'get_planned_hour_cost',
    'get_avg_hour_cost',
    #'get_planned_score',
    'get_done_score'
)
search_fields = ('facility__name',)

def changelist_view(self, request: object, extra_context: object = None) -> object:
    request.GET = request.GET.copy()
    self.month = request.GET.get('month', None)
    self.year = request.GET.get('year', None)
    if self.month or self.year:
        self.date = datetime.date(int(self.year), int(self.month), 1)
    else:
        self.date = timezone.now()
        self.month = self.date.month
        self.year = self.date.year
    extra_context = extra_context or {}
    extra_context['next'] = self.next_date
    extra_context['prev'] = self.prev_date
    extra_context['date'] = self.date

    sum_done_score = 0
    sum_done_hours = 0
    sum_done_cost_workers = 0
    sum_schedule_income_value = 0

    response = super(ScheduleAdmin, self).changelist_view(request, extra_context)
    qs = response.context_data["cl"].queryset
    #qs = self.get_queryset(request)
    for q in qs.values('id'):
        schedules = Schedule.objects.filter(id = q['id'])
        for s in schedules:
            sum_done_score += s.get_value()
            sum_done_hours += s.get_done_hours()
            sum_done_cost_workers += s.get_done_cost_workers()
            sum_schedule_income_value += s.get_schedule_income_value()

    extra_context['sum_done_score'] = sep('%.2f zł' % sum_done_score, thou=".", dec=",")
    extra_context['sum_done_hours'] = sep('%.2f h' % sum_done_hours, thou=".", dec=",")
    extra_context['sum_done_cost_workers'] = sep('%.2f zł' % sum_done_cost_workers, thou=".", dec=",")
    extra_context['sum_schedule_income_value'] = sep('%.2f zł' % sum_schedule_income_value, thou=".", dec=",")

    return super(ScheduleAdmin, self).changelist_view(request, extra_context=extra_context)

和views.py方法:

def xls_schedule_stats(request, year, month):

def get_name(obj):
    return obj.facility.name

def code(obj):
    if obj.facility.cost_category:
        return obj.facility.cost_category.number
    return ''

def get_company(obj):
    if obj.facility.cost_category.owner_company:
        return obj.facility.cost_category.owner_company.name
    return 'Brak'

def get_done_hours(obj):
    return '%.2f h' % obj.get_done_hours()

def get_done_cost_workers(obj):
    return '%.2f zł' % obj.get_done_cost_workers()

def get_avg_cost(obj):
    return '%.2f zł' % obj.get_avg_cost()

def get_avg_hour_cost(obj):
    return '%.2f zł' % obj.get_avg_hour_cost()

def get_planned_score(schedule):
    return '%.2f zł' % schedule.get_value()

def get_done_score(schedule):
    return '%.2f zł' % schedule.get_value()

HEADERS = {
    'Obiekt': get_name,
    'Numer kontrolingowy': code,
    'Spółka': get_company,
    'Godziny wykonane': get_done_hours,
    'Koszty pracowników wykonane': get_done_cost_workers,
    'Wykonany średni koszt pracownika': get_avg_cost,
    'Wykonany średni koszt godziny': get_avg_hour_cost,
    'Wynik wykonany': get_done_score,
}

queryset = Schedule.objects.filter(date__month=month, date__year=year) # I want to access to the filtered list here

writer = XlsWriter(sheet_name='Obiekty {}-{}'.format(month, year))

for col, label in enumerate(HEADERS.keys()):
    writer.write(0, col, label)

for row, schedule in enumerate(queryset, 1):
    for col, field in enumerate(HEADERS.values()):
        writer.write(row, col, field(schedule))

response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=schedule_stats {}-{}.xls'.format(year, month)
writer.save(response)

return response

0 个答案:

没有答案