Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

python 3.x - Got AttributeError when attempting to get a value for field `text` on serializer `CommentSerializer`

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It should be get_object_or_404(Comment, post = item) because get_list_or_404 is returning a list and get_object() should return a single object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...