ElasticPanda
ElasticPanda

Reputation: 123

How to count the number of subscribers

I'm using this model to allow user to subscribe or unsubscribe to a specific game. But now I'm unsure of how to count the number of users subscribed to a specific game.

class Subscription(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return str(self.id)

views.py:

class TitlePostListView(ListView):
    model = Post
    context_object_name = 'posts'
    template_name = 'posts/game.html'

    def get_queryset(self):
        title = get_object_or_404(Game, slug=self.kwargs.get('slug'))
        return Post.objects.filter(game=title).order_by('-date_published')

    def get_context_data(self, **kwargs):
        context = super(TitlePostListView, self).get_context_data(**kwargs)
        context['game'] = get_object_or_404(Game, slug=self.kwargs.get('slug'))
        context['subscription_status'] = subscription_status(self.request.user, context['game'])
        return context

Upvotes: 0

Views: 144

Answers (1)

Hybrid
Hybrid

Reputation: 7049

You would do something along the lines of this:

game = Game.objects.get(name="Some Game")  # Gets the game obj (replace "name" with the identifier you use)
subscriptions = Subscription.objects.filter(game=game)  # Filters all the subscriptions associated with the game obj above
sub_count = subscriptions.count()  # Uses QuerySet method .count() to get amount of subscription instances, and avoids a potentially costly DB hit

EDIT

To get the query into your context when using ListView, you can do something like this:

class TitlePostListView(ListView):
    model = Post
    context_object_name = 'posts'
    template_name = 'posts/game.html'

    def get_queryset(self):
        game = get_object_or_404(Game, slug=self.kwargs.get('slug'))
        return Post.objects.filter(game=game).order_by('-date_published')

    def get_context_data(self, **kwargs):
        game = get_object_or_404(Game, slug=self.kwargs.get('slug'))
        context = super(TitlePostListView, self).get_context_data(**kwargs)
        context['game'] = game
        context['subscription_status'] = subscription_status(self.request.user, context['game'])
        context['sub_count'] = Subscription.objects.filter(game=game).count()
        return context

And then in your template, you can use {{ sub_count }} to see the subscription count for that specified game.

Upvotes: 2

Related Questions