【问题标题】:How to use If else in queryset in django如何在 django 的查询集中使用 If else
【发布时间】:2021-06-06 17:49:42
【问题描述】:

我需要在我的查询集中为 Value1 使用 if else 条件..我在查询集中找到了我的记录的平均值..我需要应用类似的条件..如果我的 Value1 在 90 到 110 之间,那么我必须得到消息为“大”,如果低于 90,则必须打印为“低”,如果高于 140,则必须打印为“高”

我需要在我的 html 文件上打印这个输出

模型.py:

from django.db import models
from django.contrib.auth.models import User



class graphinput(models.Model):
  user=models.ForeignKey(User,on_delete=models.CASCADE)
  Month = models.CharField(max_length=30)
  Value1 = models.IntegerField()
  Value2 = models.IntegerField()

urls.py:

def average(request):   
     userid = None
     if request.user.is_authenticated:
         userid = request.user.id
         print(userid)
     dataset = graphinput.objects.filter(user=userid) \
    .values('Value1')
 
     a=dataset.aggregate(Sum('Value1'))
     b=dataset.aggregate(Avg('Value1'))
     print(a)
     print(b)
     return render(request, 'profile.html')
     

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您可以根据其他列的值动态创建列:

    from django.db.models import Case, Value, When
    
    Graphinput.objects.annotate(
        message=Case(
            When(value1__lt=90, then=Value('high')),
            When(value1__lt=110, then=Value('low')),
            When(value1__gt=140, then=Value('great')),
            default=Value('not set'),
        ),
    ).values_list('value1', 'message')
    

    更多详情here。此外,您应该以大写字母和小写变量开头的类名; Graphinput 和 value1

    【讨论】:

      【解决方案2】:
      avg = b.get('Value1__avg', 0)
      
      if avg < 90:
          message = 'low'
      else if avg < 110:
          message = 'great'
      else:
          message = 'high'
          
      
      context = {'message': message}
          return render(request, 'profile.html', context)
      

      接下来使用{{ message }}在模板中访问它

      【讨论】:

      • 工作!我正在尝试没有获取我的数据所以没有实现..我现在可以说 0 是什么(第二个参数)
      • 如果 'b' 中的 Value1__avg 没有值,则默认值为 0。这是 python 字典功能。
      • 我还有一个疑问..在我的 html 文件中..如果我的 avg 低于 90 或高于 110 ,我必须添加一个按钮 ..如果它的赌注 90-110 我需要显示按钮
      • tq 很有帮助
      猜你喜欢
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多