1

iam trying to count with filter and it doesn't show any error but there is no count showing

I have tried all what I know and search every where didn't find any solution :

class UsersAnswersSerializer(serializers.ModelSerializer):

 Answers = serializers.SerializerMethodField('get_answers')

 def get_answers(self, obj):
    queryset = AnswersModel.objects.filter(Question=obj.Answer.Question.id)\
        .annotate(answersCount=Count('UsersAnswer', distinct=True))

    serializer = Answersserializer(instance=queryset, many=True)

    return serializer.data
 
 class Meta:
     model = UsersAnswerModel
     fields = ['Answer', 'APNSDevice' ,'RegistrationID','Answers']

and this is my models :

class AnswersModel(models.Model):
      Question = models.ForeignKey(QuestionsModel, related_name='QuestionAnswer', on_delete=models.CASCADE)
      Answer = models.CharField(max_length=200)

class UsersAnswerModel(models.Model):
     Answer = models.ForeignKey(AnswersModel, related_name='UsersAnswer', on_delete=models.CASCADE)
     RegistrationID = models.CharField(max_length=200)
     APNSDevice = models.CharField(max_length=200,default='no name')

class QuestionsModel(models.Model):
      created = models.DateTimeField(auto_now_add=True)
      Question = models.CharField(max_length=200)
      

what is get is

{
"Answer": 12,
"APNSDevice": "byname",
"RegistrationID": "asdasdasdasdasdasdasdasdsa",
"Answers": [
    {
        "id": 10,
        "Question": 4,
        "Answer": "Answer 1",
        "UsersAnswer": [
            "gfgdgdfgdf",
            "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4"
        ]
    },
    {
        "id": 11,
        "Question": 4,
        "Answer": "Answer 2",
        "UsersAnswer": [
            "sfgdfgdf",
            "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4",
            "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4",
            "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4"
        ]
    }

I need to make "UsersAnswer" show a count of its array

Bosoud
  • 158
  • 4
  • 24

1 Answers1

1

I think what you want to do is aggregate and count.

Replace annotate with aggregate

Chymdy
  • 662
  • 4
  • 14
  • I got this error when replace with aggregate. Got AttributeError when attempting to get a value for field `Question` on serializer `Answersserializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'Question'. – Bosoud Mar 12 '21 at 07:28
  • 1
    This seems like an error with the serializer. I can't say much about this but if you want to return a count, You don't need to annotate through the query set. Just aggregate and count. – Chymdy Mar 12 '21 at 14:37