如何计算订户数量

时间:2019-03-28 20:43:10

标签: django

我正在使用此模型允许用户订阅或取消订阅特定游戏。但是现在我不确定如何计算订阅特定游戏的用户数量。

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

1 个答案:

答案 0 :(得分:2)

您可以按照以下步骤进行操作:

memory leak detected

编辑

要在使用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 时使查询进入您的上下文,可以执行以下操作:

ListView

然后在模板中,您可以使用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 查看该指定游戏的订阅计数。