1

If I am creating a list of new model objects based on some form input, e.g.,

new_items = []
for name, value in self.cleaned_data.items():
  if name.startswith('content_item_'):
      new_items.append(ContentItem(item=value))

# can I add the entire new_items list to the database in one swoop? 

I'm having trouble finding whether this in the docs, which generally refer to creating objects one at a time via the .save() method. But one-at-a-time seems inefficient when you have a whole list of objects to add.

Thanks!

B Robster
  • 40,605
  • 21
  • 89
  • 122

2 Answers2

1

I believe Brandon Konkle's reply to a similar question is still valid: Question about batch save objects in Django

In summary: Sadly, no, you'll have to use django.db.cursor with a manual query to do so. If the dataset is small, or the performance is of less importance though, looping through isn't really THAT bad, and is the simplest solution.

Also, see this ticket: https://code.djangoproject.com/ticket/661

Community
  • 1
  • 1
haeric
  • 159
  • 4
1

https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create

Edit: Unfortunately this is not on 1.3

Original Answer

Thank god for bulk_create!

You could then do something like this:

ContentItem.objects.bulk_create(new_items)

For those too lazy to click the link, here is the example from the docs:

>>> Entry.objects.bulk_create([
...     Entry(headline="Django 1.0 Released"),
...     Entry(headline="Django 1.1 Announced"),
...     Entry(headline="Breaking: Django is awesome")
... ])
Derek Kwok
  • 12,768
  • 6
  • 38
  • 58