Duplicate key value violates unique constraint error in Django

I have a model named package in an app named exam. I use Django rest framework and have the following View:

class PackageListCreaet(ListCreateAPIView):
    queryset = Package.objects.all()
    serializer_class = PackageSerializer
    permission_classes = (IsAdminAndReadOnlyForStaff,)

    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

and the following serializer:

class PackageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Package
        fields = ('pk','name','price','exams','active')

when I try creating a new package from Django admin it works just fine. But when I try creating a new package using the API above it throws the following error:

duplicate key value violates unique constraint \"exam_package_pkey\"\nDETAIL:  Key (id)=(1) already exists

I looked around a bit to find a solution and realized the problem is that the id field of exam_package table is out of sync. I tried syncing it like this and it didn't work. Then I tried removing all records (which happened with no error) and setting the primary key to 1 like this. And it still doesn't work. I looked into this link and realized maybe my probmlem is the same and maybe DRF is creating two new instances which is why I get the error. But I have no idea how to fix it.

Why is pk int the fields list? Probably this is the problem, when you are creating a Package via API you are passing 1 as pk. Try to add pk to the property read_only_fields

read_only_fields = ('pk',)

So you don't need it when you create a Package via API.

Back to Top