Home > Enterprise >  django serializer field not recognizing attribute clearly defined
django serializer field not recognizing attribute clearly defined

Time:02-21

when i try to run a view I get this error:

AttributeError: Got AttributeError when attempting to get a value for field `inreplytouser` on serializer `ContentFeedPostCommentSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'inreplytouser'.

Here is my model:

class ContentFeedPostComments(models.Model):
   inreplytouser = models.ForeignKey(SiteUsers, null=True, related_name='replytouser', blank=True, on_delete=models.CASCADE)
   inreplytotopcomment = models.BigIntegerField(null=True, blank=True)
   timecommented = models.DateTimeField(auto_now_add=True)
   user = models.ForeignKey(SiteUsers, on_delete=models.CASCADE)
   contentcreator = models.ForeignKey(ContentCreatorUsers, on_delete=models.CASCADE)
   contentfeedpost = models.ForeignKey(ContentFeedPost, on_delete=models.CASCADE)
   text = models.CharField(max_length=1000)

here is the serializer:

class ContentFeedPostCommentSerializer(ModelSerializer):
    id = IntegerField()
    inreplytouser = SiteusersSerializer()
    user = SiteusersSerializer()
    contentcreator = ContentCreatorSerializer()

    class Meta:
        model = ContentFeedPostComments
        fields = ('id','inreplytouser', 'inreplytotopcomment', 'timecommented',
                  'user', 'contentcreator', 'contentfeedpost', 'text')

here is the view:

class ContentFeedPostsComments(APIView):
    def get(self, request, *args, **kwargs):
        postid = kwargs.get('postid')
        contentfeedpost = get_object_or_404(ContentFeedPost, id=postid)
        topcomments = ContentFeedPostComments.objects.filter(contentfeedpost= contentfeedpost, inreplytotopcomment= None).order_by('timecommented')
        replycomments = ContentFeedPostComments.objects.filter( contentfeedpost = contentfeedpost, inreplytotopcomment__isnull = False).order_by('timecommented')
        serializedtopcomments = ContentFeedPostCommentSerializer(topcomments)
        serializedreplycomments = ContentFeedPostCommentSerializer(replycomments)
        payload = {
            'topcomments': serializedtopcomments.data,
            'replycomments': serializedreplycomments.data
        }
        return Response(payload)

I was reading something about source being passsed into the inreplytouser field of the serializer field but that makes no sense. Your wisdom and knowledge on this situation is greatly appreciated.

CodePudding user response:

Since querysets are a collection of objects, many=True..[DRF-doc] needs to be set in the serializer:

serializedtopcomments = ContentFeedPostCommentSerializer(topcomments, many=True)
serializedreplycomments = ContentFeedPostCommentSerializer(replycomments, many=True)
  • Related