开发者

Django: can I add a list of new model instances to the database via a single method call?

If I am creating a list of new m开发者_开发百科odel 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!


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")
... ])


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜