from django.contrib import admin from django.urls import reverse from django.db import models from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ from orchestra.admin import ExtendedModelAdmin from orchestra.admin.utils import insertattr, admin_link from orchestra.contrib.accounts.actions import list_accounts from orchestra.contrib.accounts.admin import AccountAdminMixin from orchestra.contrib.services.models import Service from .models import Plan, ContractedPlan, Rate class RateInline(admin.TabularInline): model = Rate ordering = ('service', 'plan', 'quantity') @admin.register(Plan) class PlanAdmin(ExtendedModelAdmin): list_display = ( 'name', 'is_default', 'is_combinable', 'allow_multiple', 'is_active', 'num_contracts', ) list_filter = ('is_default', 'is_combinable', 'allow_multiple', 'is_active') fields = ('verbose_name', 'name', 'is_default', 'is_combinable', 'allow_multiple') prepopulated_fields = { 'name': ('verbose_name',) } change_readonly_fields = ('name',) inlines = [RateInline] @admin.display( description=_("Contracts"), ordering='contracts__count', ) def num_contracts(self, plan): num = plan.contracts__count url = reverse('admin:plans_contractedplan_changelist') url += '?plan__name={}'.format(plan.name) return format_html('{1}', url, num) def get_queryset(self, request): qs = super(PlanAdmin, self).get_queryset(request) return qs.annotate(models.Count('contracts', distinct=True)) @admin.register(ContractedPlan) class ContractedPlanAdmin(AccountAdminMixin, admin.ModelAdmin): list_display = ('id', 'plan_link', 'account_link') list_filter = ('plan__name',) list_select_related = ('plan', 'account') search_fields = ('account__username', 'plan__name', 'id') actions = (list_accounts,) plan_link = admin_link('plan') insertattr(Service, 'inlines', RateInline)