我有一个Django应用和postgres数据库。我正在像这样批量插入:
class TestListSerializer(serializers.ListSerializer):
"""
This class only be used once we are dealing with multiple object creation
in a list fashion by having only single query for the whole insert.
:returns: the number of inserted records.
"""
def create(self, validated_data):
records = [test(**item) for item in validated_data]
if test.objects.bulk_create(records):
return len(records)
else:
return 0
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = test
fields = ('date',
'arg1',
'arg2',
'arg3',
'arg4',
'arg5')
list_serializer_class = TestListSerializer
到目前为止,它工作正常。但是,我想避免基于日期的重复数据,所以我将日期声明为唯一的,但这只会导致对INSERT查询之前的每个单独的行条目进行多次选择,这在批量处理中效率不高。我们如何处理此类问题。欢迎提出建议。谢谢。