1

I am new to the python and Django world. I don't know if there is a better way of doing the following:

#retrieve account row, correct soc code and save record.
for i in xrange(0,len(accIdList)):
    acc = account.objects.filter(id=accIdList[i])[0]
    acc.soc = getAccSocCode(acc)
    acc.save()

def getAccSocCode(acc):
    #apply business rules on acc
    # and return new soc code
    return socCode

This is what my code is doing now:

  1. Get account row from the database
  2. Pass account object to a separate method
  3. This method performs some business rules and returns new soc code
  4. Update account row

Here, I am updating each account row separately, is there a better way to this like below:

#retrieve account row, correct soc code and save record.
accList = []
for i in xrange(0,len(accIdList)):
    acc = account.objects.filter(id=accIdList[i])[0]
    acc.soc = getAccSocCode(acc)
    accList.append(acc)
accList.save()

I tried the above code but it throws an error saying AttributeError: 'list' object has no attribute 'save'

In short, how to perform bulk update in Django?

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
javanoob
  • 6,070
  • 16
  • 65
  • 88

1 Answers1

1

Use F objects - see: How to 'bulk update' with Django?.

Even if you are saving one by one you should change your code to something like:

for id in accIdList:
    acc = account.objects.get(id)
    acc.soc = getAccSocCode(acc)
    acc.save()
thanos
  • 723
  • 7
  • 9
  • Thanks. I have looked at that answer and seems like it will work only if all the rows will have same value. In my case, each row will have different value. – javanoob Oct 29 '18 at 15:31