Creating my first CRUD in Django Rest framework this error keeps popping up. Does anyone know how to fix?? Object of type CharField is not JSON serializable
models:
class Pessoa(models.Model):
id = models.AutoField(primary_key=True),
nome = models.CharField(max_length=200),
cpf = models.CharField(max_length=14, unique=True),
def __str__(self):
return self.nome
serializer:
class PessoaSerializer(serializers.ModelSerializer):
class Meta:
model = Pessoa
fields = ('id', 'nome', 'cpf')
view(set):
class PessoaListCreate(generics.ListCreateAPIView):
serializer_class = PessoaSerializer
def get_queryset(self):
queryset = Pessoa.objects.all()
ocorrencia = self.request.query_params.get('ocorrencia')
if ocorrencia is not None:
queryset = queryset.filter(pessoa=ocorrencia)
return queryset
The error message "Object of type CharField is not JSON serializable" typically indicates that Python is attempting to serialize an object that cannot be directly converted to JSON format. However, in the Django Rest Framework (DRF), CharFields should be serializable by default.
Try this changes:
# models.py
class Pessoa(models.Model):
id = models.AutoField(primary_key=True) # Removed comma
nome = models.CharField(max_length=200) # Removed comma
cpf = models.CharField(max_length=14, unique=True) # Removed comma
def __str__(self):
return self.nome
# serializer.py
class PessoaSerializer(serializers.ModelSerializer):
class Meta:
model = Pessoa
fields = ('id', 'nome', 'cpf')
# views.py
class PessoaListCreate(generics.ListCreateAPIView):
serializer_class = PessoaSerializer
def get_queryset(self):
queryset = Pessoa.objects.all()
ocorrencia = self.request.query_params.get('ocorrencia')
if ocorrencia is not None:
queryset = queryset.filter(pessoa=ocorrencia)
return queryset
python manage.py makemigrations
python manage.py migrate