在冲突“忽略”上执行“插入”原始SQL查询,替换在Django Rest框架中批量创建

时间:2018-12-12 17:52:36

标签: postgresql django-rest-framework

这是我用来创建多个对象的Listerializer。

    class listSerializer(serializers.ListSerializer):
         def create(self, validated_data):
             objs = [klass(**item) for item in validated_data]
             return klass.objects.bulk_create(objs)

但是bulk_create会因postgres中的唯一键错误而引发错误,因此我需要在同一create函数中执行此原始sql。我需要有关将validated_data转换为sql查询的帮助。

    insert into table (count,value,type,mark,created_at) values 
       (3,32,2,162,CURRENT_TIMESTAMP),
       (4,33,1,162,CURRENT_TIMESTAMP),
       (3,33,1,162,CURRENT_TIMESTAMP)
       on CONFLICT do nothing

1 个答案:

答案 0 :(得分:0)

class listSerializer(serializers.ListSerializer):   
 def create(self, validated_data):

        values = ''
        for data in validated_data:
            values+='('
            for item in data.values():
                values+=str(item)+','
            values+='CURRENT_TIMESTAMP),'


        cursor = connection.cursor()
        cursor.execute("insert into table (count,value,type,mark,created_at) values "+values[:-1]+"
   on conflict do nothing)