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,)
@method_decorator(rest_error_decorator(logger))
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
And it's worth mentioning that although I get this error the object gets created.(and so the "(id)=(1) number changes each time".)
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.