返回错误为json django rest api

时间:2017-11-13 07:56:41

标签: django django-rest-framework

初学者警报。我正在使用ListCreateAPIView进行列表和创建。每当我通过api创建时,它都会以json格式返回响应。

{"id":16,"title":"yyyyyyyy","destination_place":[1]}

但如果出现重复slug或title等错误,则返回错误,如

IntegrityError at /api/holidays/
duplicate key value violates unique constraint "holidays_holiday_slug_key"
DETAIL:  Key (slug)=(yyyyyyyy) already exists.

有没有办法以json格式返回这些错误。 我的观点

class HolidayList(ListCreateAPIView):
    queryset = Holiday.objects.all()
    serializer_class = HolidaySerializer
    permission_classes = [IsAdminUser, IsAuthenticated]

模型

class Holiday(models.Model):
   title = models.CharField(verbose_name=_("Title"), max_length=255)
   slug = models.SlugField(unique=True)
   destination_place = models.ManyToManyField(to='places.Place',related_name='destination_place',null=True,blank=True)

1 个答案:

答案 0 :(得分:1)

HolidaySerializer中,在UniqueValidator字段上添加slug

示例

from rest_framework.validators import UniqueValidator

class HolidaySerializer(serializers.ModelSerializer):
    slug = serializers.SlugField(
             max_length=255,
             validators=[UniqueValidator(queryset=Holiday.objects.all())])

    class Meta:
        model = Holiday
        fields = ('id', 'title', 'slug', 'destination_place', )

这将以JSON格式返回唯一约束错误。

您可以自定义消息。查看docs