[Fixed]-Adding Django-admin-action with conditions

1👍

You can iterate over the queryset and perform your conditions on each one seperately, instead of just applying a “global” update to all (queryset.update(Service_Level=2)).

from django.contrib.messages import SUCCESS

def allocate_service(modeladmin, request, queryset):
    platinum_customers = []
    silver_customers = []
    message = ''

    for customer in queryset:
        if customer.Age > 25 and customer.Salary >= 800 and customer.Account_Type == 'Savings':
            customer.Service_Level.service_name = 'Platinum'
            platinum_customers.append(customer.name)
        elif other_condition_here:
            customer.Service_Level.service_name = 'Silver'
            silver_customers.append(customer.name)
        customer.save()

    if platinum_customers:
        message = 'The following customers are now platinum: {}'.format(', '.join(platinum_customers))
    if silver_customers:
        message = 'The following customers are now silver: {}'.format(', '.join(silver_customers))
    if not platinum_customers and not silver_customers:
        message = 'No customer changes!'
    modeladmin.message_user(request, message, level=SUCESS)
👤nik_m

Leave a comment