首页 > 解决方案 > 如何在 Django batch_create 操作中进行 on_conflict_replace 工作?

问题描述

该领域accountmonth独特的在一起。而且我正在尝试使用数据库batch_insert数据来加快我的数据库操作。bulk_createDjango

我的数据库后端mysqlinnodb

下面是我的基表

# my db table 

class MSpendForMonth(models.Model):
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
    system_value = models.DecimalField(max_digits=16, decimal_places=2)
    checked_value = models.DecimalField(max_digits=16, decimal_places=2, null=True)
    account = models.ForeignKey(MAccount,
                                models.DO_NOTHING,
                                related_query_name="account_month",
                                related_name="account_month"
                                )
   
    month = models.IntegerField(blank=True, null=True)

    class Meta:
        db_table = 'spend_for_month'
        unique_together = (('account', 'month'),)


# db operation

bulk_data = []
try:
    with transaction.atomic():
        for spend_data in spend_month_date_sum_queryset:
            bulk_data.append(
                MSpendForMonth(
                    account_id=spend_data["account_id"],
                    month=month,
                    system_value=spend_data["sum_value"],
                )
            )
        MSpendForMonth.objects.bulk_create(bulk_data, ignore_conflicts=True )
        # MSpendForMonth.objects.bulk_update(bulk_data, fields="system_value")
except:
    import traceback as tb
    tb.print_exc()

我想system_value用一个新值替换,因为它有时会改变。

我的问题是,如果唯一键上存在冲突,我该如何bulk_create数据并替换为新值。system_valueaccount-month

它应该类似于insert_many().on_conflict_replace() -- peewee

太谢谢了。

标签: pythondjango

解决方案


推荐阅读