Я использую Django Rest Framework для выполнения get () post () в существующей базе данных.В моделях я не определил никаких отношений первичного или внешнего ключа, так как эти ограничения обрабатываются на уровне базы данных.Когда у меня есть debug = True
в файле settings.py, отображаются ошибки уровня базы данных с трассировкой.Однако, когда debug = False, я хочу отобразить ошибки в ответе.
Например: сообщение об ошибке:
IntegrityError at /dqf_api/ReceiptLog/
(1062, "Duplicate entry 'ede pivot-dummy-ede_case_76-ede pivot command 76' for key 'PRIMARY'")
Когда debug = True, это отображается.Когда debug = False, как мне отловить эту ошибку и отобразить ее?
EDIT : включая модули кода
models.py
class TestCaseCommandRun(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run'
unique_together = (('team_name', 'suite_name', 'suite_run_id', 'case_name', 'command_name'),)
class TestCaseCommandRunResults(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run_results'
unique_together = (('suite_run_id', 'command_run_id', 'rule_name', 'result_id'),)
views.py
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name', 'result_id',
'result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
class ReceiptLogViewSet(CreateAPIView):
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
serializers.py
class TestCaseCommandRunResultsViewSet(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunResultsViewSet
fields = ['suite_run_id','command_run_id','rule_name', 'result_id','result','expected_values','actual_values','report_values','extended_values']
class TestCaseCommandRunSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunSerializer
fields = ['team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status']
class ReceiptLogSerializerClass(serializers.Serializer):
team_name = serializers.CharField(max_length=30)
suite_name = serializers.CharField(max_length=100)
suite_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default=datetime.now().strftime('%Y%m%d%H%M%S'))
case_name = serializers.CharField(max_length=50)
command_name = serializers.CharField(max_length=50)
command_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default='Not Applicable')
run_start = serializers.DateTimeField(default=datetime.now, required=False)
run_end = serializers.DateTimeField(default=datetime.now, required=False)
result = serializers.CharField(max_length=10, default='Not Applicable')
run_status = serializers.CharField(max_length=10)
rule_name = serializers.CharField( max_length=50, required=False, allow_blank=True, default='Not Applicable')
expected_values = serializers.CharField(max_length=200, allow_blank=True)
actual_values = serializers.CharField(max_length=200, allow_blank=True)
report_values = serializers.CharField(max_length=200, allow_blank=True)
extended_values = serializers.CharField(max_length=200, allow_blank=True)
def create(self, validated_data):
team_name = validated_data.get('team_name', None)
suite_name = validated_data.get('suite_name', None)
suite_run_id = validated_data.get('suite_run_id', None)
case_name = validated_data.get('case_name', None)
command_name = validated_data.get('command_name', None)
command_run_id = validated_data.get('command_run_id', None)
run_start = validated_data.get('run_start', None)
run_end = validated_data.get('run_end', None)
result = validated_data.get('result', None)
run_status = validated_data.get('run_status', None)
rule_name = validated_data.get('rule_name', None)
expected_values = validated_data.get('expected_values', None)
actual_values = validated_data.get('actual_values', None)
report_values = validated_data.get('report_values', None)
extended_values = validated_data.get('extended_values', None)
test_case_command_run_data = {
'team_name': team_name,
'suite_name': suite_name,
'suite_run_id': suite_run_id,
'case_name': case_name,
'command_name': command_name,
'command_run_id': command_run_id,
'run_start': run_start,
'run_end': run_end,
'result': result,
'run_status': run_status
}
TestCaseCommandRunSerializer.create(TestCaseCommandRunSerializer(), validated_data=test_case_command_run_data)
test_case_command_run_result_data = {
'suite_run_id': suite_run_id,
'command_run_id': command_run_id,
'rule_name': rule_name,
'result_id': self.result_id,
'result': result,
'expected_values': expected_values,
'actual_values': actual_values,
'report_values': report_values,
'extended_values': extended_values,
}
TestCaseCommandRunResultsSerializer.create(TestCaseCommandRunResultsSerializer(), validated_data=test_case_command_run_result_data)
self.result_id += 1
return validated_data
urls.py
router = routers.DefaultRouter()
router.register(r'test_case_command_runs', views.TestCaseCommandRunViewSet)
router.register(r'test_case_command_run_results', views.TestCaseCommandRunResultsViewSet)
urlpatterns = [
url(r'^dqf_api/', include(router.urls)),
url(r'^dqf_api/ReceiptLog/', views.ReceiptLogView.ReceiptLogViewSet.as_view(), name='ReceiptLog')]
РЕДАКТИРОВАТЬ: код исправления
Добавил это в serializers.py
def create(self, validated_data):
try:
return super().create(validated_data)
except IntegrityError as e:
error_msg = "IntegrityError occurred while creating entry in test_case_command_run_result model. Detailed Error: %s" %e
raise serializers.ValidationError(error_msg)