views:

39

answers:

3

Hi all,

I have a lot of objects to save in database, and so I want to create Model instances with that.

With django, I can create all the models instances, with MyModel(data), and then I want to save them all.

Currently, I have something like that:

for item in items:
    object = MyModel(name=item.name)
    object.save()

I'm wondering if I can save a list of objects directly, eg:

objects = []
for item in items:
    objects.append(MyModel(name=item.name))
objects.save_all()

To save all the objects in one transaction. any idea to do that ? Thanks !

+1  A: 

The easiest way is to use the create Manager method, which creates and saves the object in a single step.

for item in items:
    MyModel.objects.create(name=item.name)
Daniel Roseman
+1. If `name` is unique and duplicate inputs are possible then it would be a good idea to use `get_or_create`.
Manoj Govindan
A: 

for a single line implementation, you can use lambda...

lambda x:MyModel.objects.get_or_create(name=x), items

Here, lambda matches each item in items list to x and create a Database record...

Lambda Documentation

FallenAngel
You probably want to mention that the `lambda` has to be `map` ped over `items`: `map(lambda name: MyModel.objects.get_or_create(name = name), items)`
Manoj Govindan
Ja, thats another way i try to say (:
FallenAngel
A: 

Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.

I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.

http://djangosnippets.org/snippets/446/

OmerGertel