title: UnboundLocalError while using Django Querysets
body: <p>I am trying to implement the following Django Queryset in my webapp:</p>
  <pre><code>from django.db.models import When, Case, Value, Sum, IntegerField, F
  from django.shortcuts import render,redirect
  from hr.models import *
  
  def mobile_recharge(request):
      S=['0']
      T=['1']
      B=['A','B','C']
      db_obj1=BillsPayment.objects.using('MBDB').all()
      db_obj2=BillsService.objects.using('MBDB').all()
      while db_obj1.values('BILLER_ID')==db_obj2.values('BILLS_SERVICE_CODE') and db_obj2.values('BILLS_TYPE')=='3':
          data = db_obj1.annotate(
                              Transaction_type=F('BILLER_ID'),
                              Success=Sum(Case(
                                  When(ERROR_CODE__in=S, then=Value(1)),
                                  default=Value(0),
                                  output_field=IntegerField()
                              )),
                              Technical_declines=Sum(Case(
                                  When(ERROR_CODE__in=T, then=Value(1)),
                                  default=Value(0),
                                  output_field=IntegerField()
                              )),
                              Business_declines=Sum(Case(
                                  When(ERROR_CODE__like='B',then=Value(1)),
                                  When(ERROR_CODE__in=B, then=Value(1)),
                                  When(ERROR_CODE__isnull=True, then=Value(1)),
                                  default=Value(0),
                                  output_field=IntegerField()
                              ))
                          ).order_by(Transaction_type)
  
      return render(request,'hr/test.html',{'model':data})
  </code></pre>
  <p>Which is supposed to execute the following SQL Query:</p>
  <pre><code>SELECT 'MOB' AS TYPE,
         SUM(case when BP.ERROR_CODE in ('0')
             then 1 else 0 end) SUCCESS,
         SUM(case when BP.ERROR_CODE in ('1')
             then 1 else 0 end) TECHNICAL_DECLINES,
         SUM(case when (BP.ERROR_CODE LIKE '%ERR%' OR BP.ERROR_CODE in ('A','B','C') or BP.ERROR_CODE is null )
             then 1 else 0 end) BUSINESS_DECLINES
  FROM BP,BS
  WHERE BP.BILLER_ID=BS.BILLS_CODE
  AND BS.BILLS_TYPE='3';
  </code></pre>
  <p>When I run the server using the <code>python manage.py runserver</code> command however the browser is giving the UnboundLocalError:</p>
  <p><a href="https://i.stack.imgur.com/L5kL1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L5kL1.jpg" alt="enter image description here" /></a></p>
  <p>Please help me with this. Thank you.</p>