IF ELSE陈述以选择模型

时间:2019-06-20 05:01:30

标签: python django-models

我想找出是否可能(也许我只是做错了),我的模型有两个选择,我想创建一个if语句,当我选择一个选项时,它将自动选择下一个模型的正确选择。我也只想知道这是最佳实践还是还有另一种方法

class CalculatorModel(models.Model):
    premium_investment_value_choice = [(10000,'10,000.00'),
                                (15000,'15,000.00'),
                                (18000,'18,000.00'),
                                (20000,'20,000.00'),
                                (30000,'30,000.00')]
    premium_value_choice = [(36,'36.00'),
                            (49,'49.05'),
                            (57,'57.06'),
                            (62.'62.00'),
                            (93.'93.00')]
    premium_payer_name = models.CharField(max_length = 13)
    premium_payer_id = models.CharField(max_length = 13)
    premium_investment_value = models.CharField(max_length = 9, choices = premium_investment_value_choice, default=10000  )
    premium_value = models.CharField(max_length=10, choices = premium_value_choice, default = 36)


    def value(self):
        if self.premium_investment_value == 10000:
            self.premium_value_choice = 36
            return self.premium_value_choice
        elif self.premium_investment_value == 15000:
            self.premium_value_choice = 49
            return self.premium_value_choice
        elif self.premium_investment_value == 15000:
            self.premium_value_choice = 57
            return self.premium_value_choice
        elif self.premium_investment_value == 15000:
            self.premium_value_choice = 62
            return self.premium_value_choice
        elif self.premium_investment_value == 15000:
            self.premium_value_choice = 93
            return self.premium_value_choice

1 个答案:

答案 0 :(得分:0)

使用字典供参考的一种非常简单的方法:

CHOICES = {'10k': 36.00,
           '15k': 49.05,
           '18k': 57.06,
           '20k': 62.00,
           '30k': 93.00}

def value(sel='10k'):  # this is the default
    if sel in CHOICES:
        return CHOICES[sel]

欢呼