Fafa Calvs
Fafa Calvs

Reputation: 3

Raw Update Query inside a while loop in Django Python

Ok im new to python especially django so please be easy on me.

i just want to iterate through my resultset per row, then use its values for update query inside the while loop. so far i have this code.

def orprocesspost(request, pk):

cursor = connection.cursor()
#this query returns 2 rows
cursor.execute('select ord_recno, orm_recno, account_code, debit, credit, created_by, posted, remarks, origin, sort_order from or_details where orm_recno=%s', [pk])

row = cursor.fetchone()

while row is not None:

    cursor.execute('update general_ledger set dr_bal = dr_bal + %s, cr_bal = cr_bal + %s where gl_code = %s',[row[3],row[4],row[2]])
    row = cursor.fetchone()

if i remove this line cursor.execute('update general_ledger set dr_bal = dr_bal + %s, cr_bal = cr_bal + %s where gl_code = %s',[row[3],row[4],row[2]])

the loop executes fine and i can see the second row being read

but when i try to use the update query it only updates 1 row... i don't know whats happening here. i've been searching for the solution for hours..

by the way i followed this tutorial Fetching row by row from MySQL in Python

Thanks and regards

Upvotes: 0

Views: 718

Answers (1)

soumya yelamali
soumya yelamali

Reputation: 144

You can try using Django ORM to query database. Its very easy to understand.

def orprocesspost(request, pk):
  try:
     obj = or_details.objects.filter(orm_recno=pk)
     for i in obj:
        new_obj = general_ledger.objects.get(gl_code=i.xyz)  
        #xyz : name of your model field.
        newobj.dr_bal = newobj.dr_bal + <new value>
        newobj.cr_bal = newobj.cr_bal + <new value>
        newobj.save()

  exept or_details.DoesNotExist:
    print "object does not exist"

Upvotes: 1

Related Questions