Django bulk_create重复字段的更新

时间:2014-08-18 15:03:58

标签: django postgresql

我有一个镜像外部数据源的模型,有时外部数据会更改旧记录。我想从外部数据中批量创建对象以提高速度,但我找不到任何关于更新重复字段的文档。

示例模型:

class Author(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)

class Book(models.Model):

    author = models.ForeignKey('Author')
    title = models.CharField(max_length=255)
    price = models.FloatField()  # Sometimes changes

    class Meta:
        unique_together = ('author', 'title')

在创建循环中运行它非常慢(几千条记录几分钟),因为每本书都需要两个事务:一个用于get_or_create作者,另一个用于get_or_create Book。是否可以使用诸如bulk_create之类的东西,并在书籍与作者和标题匹配时更新价格?

1 个答案:

答案 0 :(得分:0)

在下文中,我假设您的外部数据源与以下形式“形态等效”:

books = [{'title': 'Title1', 'author': 'author name 1', 'price': 23.50},
         {'title': 'Title2', 'author': 'author name 2', 'price': 24.50}, ...]

然后你可以用这种方式更新你的模型

books_queryset = Book.objects.select_related()

for book in books:
   try:
     item = books_queryset.get(title=book['title'], author__last_name=book['author'])
     item.price = book['price']
     item.save()
   except ObjectDoesNotExist:
     # Add new item
相关问题