【问题标题】:how to minimize the code using python django如何使用 python django 最小化代码
【发布时间】:2019-09-08 10:31:54
【问题描述】:

我有一个嵌套的 if 条件来检查条件。我怎样才能最小化代码?我应该怎么做才能缩短代码? 我创建了一个函数,并在函数内部检查用户提供的仪表 ID 并更新数据库中的表。

def updatereport(meterdetails_id, indicator='inr'):

if meterdetails_id == 1:

    happycount1 = Report.objects.filter(date = timezone.datetime.today()).values("happycount")

    if len(happycount1)<=0:
        Report.objects.create(date = timezone.datetime.today(),happycount=0)
    else:

        if indicator == 'inr':

            Report.objects.filter(date=timezone.datetime.today()).update(happycount=happycount1.get()["happycount"]+1)
        else:

            Report.objects.filter(date=timezone.datetime.today()).update(happycount=happycount1.get()["happycount"] - 1)
elif meterdetails_id == 3:
    disappointedcount1 = Report.objects.filter(date = timezone.datetime.today()).values("disappointedcount")
    if len(disappointedcount1) <= 0:
        Report.objects.create(date=timezone.datetime.today(), disappointedcount=0)

    else:

        if indicator == 'inr':
            Report.objects.filter(date = timezone.datetime.today()).update(disappointedcount = disappointedcount1.get()["disappointedcount"] + 1)

        else:

            Report.objects.filter(date = timezone.datetime.today()).update(disappointedcount = disappointedcount1.get()["disappointedcount"]-1)
elif meterdetails_id == 2:
    depressedcount1 = Report.objects.filter(date = timezone.datetime.today()).values("depressedcount")
    if len(depressedcount1) <= 0:
        Report.objects.create(date = timezone.datetime.today(), depressedcount=0)
    else:
        if indicator=='inr':
            Report.objects.filter(date = timezone.datetime.today()).update(depressedcount = depressedcount1.get()["depressedcount"] + 1)
        else:

            Report.objects.filter(date = timezone.datetime.today()).update(depressedcount = depressedcount1.get()["depressedcount"] - 1)

elif meterdetails_id == 5:
    okcount1 = Report.objects.filter(date = timezone.datetime.today()).values("okcount")
    if len(okcount1) <= 0:
        Report.objects.create(date = timezone.datetime.today(), okcount=0)
    else:
        if indicator =='inr':
            Report.objects.filter(date = timezone.datetime.today()).update(okcount = okcount1.get()["okcount"] + 1)
        else:

            Report.objects.filter(date = timezone.datetime.today()).update(okcount = okcount1.get()["okcount"] - 1)

    elif meterdetails_id == 6:
    sadcount1 = Report.objects.filter(date = timezone.datetime.today()).values("sadcount")
    if len(sadcount1) <= 0:
        Report.objects.create(date = timezone.datetime.today(), sadcount=0)
    else:
        if indicator =='inr':
            Report.objects.filter(date = timezone.datetime.today()).update(sadcount = sadcount1.get()["sadcount"] + 1)
        else:

            Report.objects.filter(date = timezone.datetime.today()).update(sadcount = sadcount1.get()["sadcount"] -1)
      elif meterdetails_id == 7:
    angrycount1 = Report.objects.filter(date = timezone.datetime.today()).values("angrycount")
    if len(angrycount1) <= 0:
        Report.objects.create(date = timezone.datetime.today(), angrycount = 0)
    else:
        if indicator =='inr':
            Report.objects.filter(date = timezone.datetime.today()).update(angrycount = angrycount1.get()["angrycount"] + 1)
        else:
            # print ('here')
            Report.objects.filter(date = timezone.datetime.today()).update(angrycount = angrycount1.get()["angrycount"] - 1)

models.py

 class Report(models.Model):
happycount=models.IntegerField(default=0,null=True,blank=True)

disappointedcount=models.IntegerField(default=0,null=True,blank=True)
depressedcount=models.IntegerField(default=0,null=True,blank=True)
okcount=models.IntegerField(default=0,null=True,blank=True)
sadcount=models.IntegerField(default=0,null=True,blank=True)
angrycount=models.IntegerField(default=0,null=True,blank=True)
date=models.DateField('date',default=timezone.datetime.today(),null=True,blank=True)

def __unicode__(self):
    return '%s' % self.date

ordering = ["date"]
verbose_name = "report"
verbose_name_plural = "reports"

【问题讨论】:

    标签: python-2.7 django-rest-framework


    【解决方案1】:
    def updatereport(meterdetails_id, indicator='inr'):
        if meterdetails_id == 1:
            proper_function_name('happycount', indicator)
        elif meterdetails_id == 3:
            proper_function_name('disappointedcount', indicator)
        elif meterdetails_id == 2:
            proper_function_name('depressedcount', indicator)    
        elif meterdetails_id == 5:
            proper_function_name('okcount', indicator)
        elif meterdetails_id == 6:
            proper_function_name('sadcount', indicator)
        elif meterdetails_id == 7:
            proper_function_name('angrycount', indicator)
    
    
    def proper_function_name(count_name, indicator):
        count = Report.objects.filter(date=timezone.datetime.today()).values(count_name)
        if len(count) <= 0:
            Report.objects.create(date=timezone.datetime.today(), **{count_name: 0})
        else:
            if indicator =='inr':
                Report.objects.filter(date=timezone.datetime.today()).update(**{count_name: count.get()[count_name] + 1})
            else:
                Report.objects.filter(date=timezone.datetime.today()).update(**{count_name: count.get()[count_name] - 1})
    

    我调用了函数proper_function_name,但你应该想出更好的方法:P 还可以考虑使用 Enum 而不是硬编码的meterdetails_ids,例如:

    class MeterDetail(Enum):
        happycount=1
        disappointedcount=3
        ...
    

    所以在后面的代码中你会有

    if meterdetails_id == MeterDetail.happycount:
       ...
    

    代替:

    if meterdetails_id == 1:
        ...
    

    【讨论】:

    • 另外我不确定你的意图是什么:Report.objects.filter(date = timezone.datetime.today()).values("okcount")?
    • 我在数据库表中得到 ok 的计数,如 id |快乐计数 |失望计数 |郁闷数 |还行|生气计数 |日期 |悲伤计数 ----+------------+-------+----------- -----+---------+------------+------------+-------- - 15 | 6 | 1 | 1 | 1 | 1 | 2019-04-05 | 1
    • 我是 python 新手..你能告诉我为什么在函数 Report.objects.create(date=timezone.datetime.today(), **{count_name: 0} 中使用 ** ) 但不是在这里 def proper_function_name(count_name, indicator): ?@marke
    • 在第一个中,变量 count_name 中的任何字符串都将作为关键字参数的名称传递,“:”之后的任何内容作为该关键字参数的值。在第二个函数中,您可以使用位置参数,不需要关键字参数。 **{...} 表示法称为关键字解包,谷歌一下:P
    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2010-09-27
    • 2021-05-07
    相关资源
    最近更新 更多