这是我用来创建多个对象的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
答案 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)