Django bulk_create with ignore rows that cause IntegrityError?

后端 未结 6 1704
孤城傲影
孤城傲影 2020-12-03 02:46

I am using bulk_create to loads thousands or rows into a postgresql DB. Unfortunately some of the rows are causing IntegrityError and stoping the bulk_create process. I was

6条回答
  •  無奈伤痛
    2020-12-03 02:57

    Even in Django 1.11 there is no way to do this. I found a better option than using Raw SQL. It using djnago-query-builder. It has an upsert method

    from querybuilder.query import Query
    q = Query().from_table(YourModel)
    # replace with your real objects
    rows = [YourModel() for i in range(10)] 
    q.upsert(rows, ['unique_fld1', 'unique_fld2'], ['fld1_to_update', 'fld2_to_update'])
    

    Note: The library only support postgreSQL

    Here is a gist that I use for bulk insert that supports ignoring IntegrityErrors and returns the records inserted.

提交回复
热议问题