TypeError : count() takes at least 1 argument (0 given)

Viewed 7964

i am getting TypeError: count() takes at least 1 argument (0 given).

it would be great if anybody could figure out where i am doing thing wrong. thank you so much in advance.

class CommentsSerializer(serializers.ModelSerializer):
    comment_count = serializers.SerializerMethodField()
    class Meta:
        model = Comments
        fields = [
            "id", "title", "name", "subject", "comment_count",
        ]

    def get_comment_count(self, obj):
        return obj.subject.count()

4 Answers

Your implementation does not make sense. I think you are trying to get count of all the Comments object, but here you are trying to count subject, probably that is a string or a list. On them, count works like this:

IN  >> "aaaaa".count('a')
OUT >> 5
IN  >> [1,2,3,4].count(1)
OUT >> 1

Now, to fix your problem, we need to understand what you want to achieve here. If you want to get count of comments for a particular post, then you can try like this:

If you have a model like this:

class Comments(models.Model):
    post = models.ForeignKey(Post)

Then you can take this approach:

def get_comment_count(self, obj):
    return obj.post.comments_set.count()

This is count() function from Django queryset. And obj.post.comments_set will return a queryset(for having a reverse relationship). If you have defined related_name="post_comments"(docs), then it will become obj.post.post_comments.count().

You may check the function description here

It counts the occurrence of an object in a list, so you need to pass an object as a parameter to count() function, and apply this on a list.

Also, it would be better if you give a sample program that you got the error.

count() requires exactly one argument and returns the number of instances of the provided argument in the list.

If you just want to count number of elements in a list, use:

return len(obj.subject)

count requires an argument. It returns the number of instances of a particular item in a list.

    l=[1,2,5,4,5,6,7,10]
    l.count(5)
    2

2 here is the number of 5s in the list.

Related