Jharwood
Jharwood

Reputation: 1056

How do I combine django querys to allow me to save in one go?

As it stands, I have a deserialiser that can import any model I throw at it and put it into my database. unfortunately it hits the database with every single model and I want to stop this.

Is there any way for me to lump lots of short saves into one big one?

Example code:

def deserialise(xml):
    for x in model_list:
         do work to make instance...
         instance.save()
    return True

is there any way to move the saving of instance out of the for loop?

Upvotes: 1

Views: 94

Answers (1)

Shawn Chin
Shawn Chin

Reputation: 86844

You can use transaction.commit_manually().

from django.db import transaction

@transaction.commit_manually
def deserialise(xml):
    for x in model_list:
         # do work to make instance...
         instance.save()
    transaction.commit()
    return True

Or transaction.commit_on_success() which will automatically commit the saves when and if the function returns successfully.

from django.db import transaction

@transaction.commit_on_success
def deserialise(xml):
    for x in model_list:
         # do work to make instance...
         instance.save()
    return True

Alternatively, in django 1.4 there's also bulk_create(), but do note the caveats listed in documentation.

Upvotes: 4

Related Questions