Home > OS >  'Tag' object has no attribute 'count' in for loop
'Tag' object has no attribute 'count' in for loop

Time:09-22

I am building a BlogApp and I am trying to create a notification when a particular tag is used 10 times.

So i am using if statement in for loop so if any tag used 10 times then create notification But when i try to count then it is showing

'Tag' object has no attribute 'count'

models.py

class Post(models.Model):
    post_user = models.ForeignKey(User, on_delete=models.CASCADE)
    psot_title = models.CharField(max_length=30)

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_of = models.ForeignKey(Post, on_delete=models.CASCADE)

views.py

def page(request):
    subquery = Tag.objects.filter(post__post_user=request.user).annotate(
                                                num_name=Count('name')

    for que in subquery:
        if que.count() > 10:
            Notification.objects.create(user=request.user)

    context = {'subquery':subquery}
    return render(request, 'page.html', context}

What have i tried :-

I also tried len like :-

    for que in subquery:
        if len(que) > 10:
            Notification.objects.create(user=request.user)

But it showed

object of type 'Tag' has no len()

I have tried many times by removing count() and len() but it showed

'int' object has no attribute 'name'

If I use count() in query then it will count in all tags But i am trying to check every tag.

Any help would be much Appreciated. Thank You

CodePudding user response:

You're using annotations in your query to add the count information onto the Tag object, e.g.

.annotate(num_name=Count('name')

This calculates the count of name and annotates the tag object with that value. To access this count for a given tag, you then need to use:

tag.num_name

So, in your code:

    for que in subquery:
        if que.num_name > 10:
            Notification.objects.create(user=request.user)
  • Related