[Answer]-Is it possible to improve the process of instance creation/deletion in Django using querysets?


First, in this line

if not Pupil.objects.filter(name=name):

It looks like the name variable is undefined no ?

Then here is a shortcut for your code I think:

def update_pupils(teacher, updated_list):
    # Step 1 : delete
    Pupil.objects.filter(teacher=teacher).exclude(name__in=updated_list).delete() # delete all the not updated objects for this teacher

    # Step 2 : update
      # either
    for name in updated_list:
        Pupil.objects.update_or_create(name=name, defaults={teacher:teacher}) # for updated objects, if an object of this name exists, update its teacher, else create a new object with the name from updated_list and the input teacher
      # or (but I'm not sure this one will work)
    Pupil.objects.update_or_create(name__in=updated_list, defaults={teacher:teacher})

Another solution, if your Pupil object only has those 2 attributes and isn’t referenced by a foreign key in another relation, is to delete all the “Pupil” instances of this teacher, and then use a bulk_create.. It allows only 2 access to the DB, but it’s ugly

EDIT: in first loop, pupil also is undefined

Leave a comment