0

In annotate. When counting records, how can I use a custom query to narrow down what to count?

class User(models.Model):
    name = models.CharField(max_length=50)
class Tweet(models.Model):
    user = models.ForeignKey("User", related_name="tweet")
    favorite = models.IntegerField(default=0)
    is_active = models.BooleanField(default=False)

    objects = TweetQuerySet.as_manager()


class TweetQuerySet(models.QuerySet):
    def buzzed(self):
        return self.filter(
            is_active=True,
            favorite__gte=100
        )
# I want to count only the tweets returned using the buzzed query.
users = User.objects.annotate(tweet_count=Count("tweet"))

Thanks in advance.

y.dai
  • 33
  • 4

1 Answers1

0

This is related to How to filter objects for count annotation in Django?

Just like stated in post above, you can use filter argument in Count class.

In your case, you could do something like:

users = User.objects.annotate(tweet_count=Count("tweet", filter=Q(is_active=True) & Q(favorite__gte=100)))

If you'd like to have this logic in TweetQuerySet manager, you can make a method, that returns this exact code, like this:

def buzzed_tweets_count(self):
    return self.annotate(tweet_count=Count("tweet", filter=Q(is_active=True) & Q(favorite__gte=100)))

And then call it:

users = User.objects.buzzed_tweets_count()
COSHW
  • 146
  • 8