Reputation: 694
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()
Upvotes: 2
Views: 13585
Reputation: 51988
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()
.
Upvotes: 3
Reputation: 823
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 5
s in the list.
Upvotes: 1
Reputation: 9504
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)
Upvotes: 1