添加条件为

时间:2017-04-17 04:13:20

标签: python django django-admin-actions

我的django模型Customer由这些字段组成;

'Customer_ID','姓名','性别', '年龄' , “国籍”,“地址”, 'Account_Type' '薪水' '余额' 'Employer_Stability' 'Customer_Loyalty' 'Residential_Status' 和的 'Service_Level'

其中Service_Level = SilverGoldPlatinum

我已设法创建一个自定义管理操作,只是更新Service_Level而没有任何条件,如下所示;

def allocate_service(ModelAdmin, request, queryset):
    queryset.update(Service_Level=2)

@admin.register(models.Customer)
class CustomerAdmin(admin.ModelAdmin):
    icon = '<i class="material-icons">account_box</i>'
    list_display = ('Customer_ID', 'Name', 'Gender', 'Nationality', 
                'Account_Type', 'Salary', 'Balance', 'Service_Level')
    list_per_page = 10
    list_filter = ('Nationality', 'Gender')
    actions = [allocate_service ]

我想添加一个操作,根据上面的粗体功能(Age,Salary等)的值将Service_Level分配给客户/客户。 例如 当Age > 25 and Salary >= 800 and Account_Type == Savings然后Service_Level = Platinum

我的模型如下:

class Service(models.Model):
#service_no = models.CharField(primary_key=True, max_length=4)
service_name = models.CharField(primary_key=True, max_length=40)
service_description = models.TextField(default='')

class Meta:
    db_table = 'services'
    ordering = ['service_name']

def __str__(self):
    return self.service_name

# Customer Model: too big so I ommited the other fields here

class Customer(models.Model):
    Service_Level = models.ForeignKey(Service, on_delete=models.CASCADE, 
        db_column='service_name', null=True, blank=True)

我删除了在Service_Level上使用int键的选项

我不确定我应该怎么做。帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您可以迭代查询集并分别对每个查询集执行条件,而不是仅将“全局”update应用于所有(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)