Reputation: 163
Just started with Django Rest framework and following the great tutorial: https://sunscrapers.com/blog/ultimate-tutorial-django-rest-framework-part-1/
I have created a test model:
models.py
class Test(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField
And to make the object available through the API, I have implemented a serializer. This would serialize to XML, YAML or JSON, the latter is what I am interested in. Below is my serialization class.
serializers.py
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = models.Test
fields = ('name', 'age')
app/views.py
class TestViewSet(viewsets.ModelViewSet):
queryset = models.Test.objects.all()
serializer_class = serializers.TestSerializer
However, it doesn't seem to serialize to JSON as expected as the error below shows:
File "C:\Program Files\Python38\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable
Worth adding, that it worked for like 2 hours then just went bad.
Upvotes: 0
Views: 7019
Reputation: 82
Not sure if this would be useful to anyone but I ran into the same issue and mine was a trailing comma(,) at the end of that line.
Upvotes: 0
Reputation: 1124
You missed a pair of parentheses in your Test
class's age
field:
class Test(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField() # <-- missed this pair
Upvotes: 2