[Answer]-Python Django โ€“ Comparing an Array with a Model

1๐Ÿ‘

โœ…

You can replace this code

emptyRow = []
for idx, val in enumerate(missingValues):
    found = False
    for items in sequential_missing.objects.all():
        if(items.row == val and items.database == databaseName):
            found = True
            #print "Database:" + str(items.row) + ", Same as Empty Row:" + str(val)
    if(found == True):
        emptyRow.append(val)

with

emptyRow = sequential_missing.objects.filter(database=databaseName,row__in = missingValues)

so that you issue a single query to the database. However this will concatenate all missingValues in a string which must be inserted in the query. You should try and see if it is viable.

Otherwise you should order both missingValues and sequential_missing.objects by val, so that you can find items in a linear time. Something like:

sort(missingValues)
val_index = 0
for item in sequential_missing.objects.all().order_by('row'):
  while (val_index < len(missingValues) and item.row>missingValues[val_index]):
    val_index += 1
  if (item.row == missingValues[val_index]): 
    emptyRow.append(item.row)

Leave a comment