I am using Django Rest Framework to make a Blog API. But I have been getting this error when I search for individual comments under each post.
The model, serializers and views for Comments is given below:
Models.py
class Comment(models.Model) :
text = models.TextField(
validators=[MinLengthValidator(3, "Comment must be greater than 3 characters")]
)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# Shows up in the admin list
def __str__(self):
return (self.post.title)
Serializers.py
class CommentSerializer(serializers.ModelSerializer):
owner = serializers.StringRelatedField()
post = serializers.StringRelatedField()
class Meta:
model = Comment
fields = ['text', 'created_at', 'post', 'owner']
Views.py
class CommentViewSet(viewsets.ModelViewSet):
serializer_class = CommentSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get_object(self, queryset = None, **kwargs):
item = self.kwargs.get('pk')
return get_list_or_404(Comment, post = item)
def get_queryset(self):
return Comment.objects.all()
Whenever I go to http://localhost:8000/api/comments/1/ this is what happens.
Got AttributeError when attempting to get a value for field `text` on serializer `CommentSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `list` instance.
Original exception text was: 'list' object has no attribute 'text'.
question from:
https://stackoverflow.com/questions/66065071/got-attributeerror-when-attempting-to-get-a-value-for-field-text-on-serializer 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…