AttributeError: Got AttributeError when attempting to get a value for field `comments` on serializer `Post`
**In my blog app when i used to retrive all the posts I got this error.
**
This is the error message I got:
AttributeError: Got AttributeError when attempting to get a value for field comments
on serializer Post
.
The serializer field might be named incorrectly and not match any attribute or key on the Post
instance.
Original exception text was: 'Post' object has no attribute 'comments'.
I attached my code below. Help me how to get rid out of this.
models.py
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
#Abstract Start
class TimeStamp(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Selection(TimeStamp):
name = models.CharField(max_length=100)
class Meta:
abstract = True
ordering = ['name']
#Abstract End
class Post(Selection):
# name = title
author = models.ForeignKey(User,on_delete=models.CASCADE)
body = models.TextField(_("content"))
slug = models.SlugField(_("slug"))
likes = models.IntegerField(_("likes"),default=0)
def __str__(self):
return self.name
class Comment(TimeStamp):
user = models.ForeignKey(User,on_delete=models.CASCADE)
content = models.TextField(_("comments"))
likes = models.IntegerField(_("likes"),default=0)
post = models.ForeignKey(Post,on_delete=models.CASCADE)
def __str__(self):
return self.content
serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
from . import models
class UserSr(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
class Comment(serializers.ModelSerializer):
user = UserSr()
class Meta:
model = models.Comment
exclude = ['created_at','updated_at']
class Post(serializers.ModelSerializer):
author = UserSr()
comments = Comment(many = True)
class Meta:
model = models.Post
exclude = ['created_at','updated_at']
views.py
from django.contrib.auth.models import User
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .. import serializers,models
@api_view(['POST'])
def post_create(request):
post_serializer = serializers.Post(data=request.data)
if post_serializer.is_valid():
post_serializer.save()
return Response(post_serializer.data, status=status.HTTP_201_CREATED)
return Response(post_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'])
def postGet(request):
posts = models.Post.objects.all()
serializer = serializers.Post(posts,many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
urls.py
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from . import views
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path("blog/",views.registration_view,name='useradd'),
path('posts/',views.postGet,name='posts'),
path('posts/create/', views.post_create, name='post-create'),
]
I don't know how to get rid out of this I've stucked it in for hours. I refered lot of projects but i could not figure it out.
class Post(serializers.ModelSerializer):
author = UserSr()
comments = serializers.StringRelatedField(many=True)
class Meta:
model = models.Post
fields = ("id","author","comments")
You can try this.
You should not use Comment
a model in Serializers as a field