【问题标题】:using models.manager to count the number of votes使用 models.manager 统计票数
【发布时间】:2019-06-05 21:53:47
【问题描述】:

我正在使用 models.manager 来计算票数,但我不明白为什么票数没有显示出来。投票系统工作(与管理员核实)但经理不工作。

models.py

class PostVoteCountManager(models.Manager):
    def get_query_set(self):
        return super(PostVoteCountManager, self).get_query_set.annotate(
            votes=Count('vote')).order_by("-votes")

class Post(models.Model):
    rank_score = models.FloatField(default=0.0)
    with_votes = PostVoteCountManager()

class Vote(models.Model):
    voter = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return "%s voted %s" %(self.voter.username, self.post.title)

我的意见.py

class PostListView(ListView):
    model = Post
    template_name = 'community/home.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    #ordering = ['-date_posted']
    queryset = Post.with_votes.all()

    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated:
            voted = Vote.objects.filter(voter=self.request.user)
            posts_in_page = [post.id for post in context["object_list"]]
            voted = voted.filter(post_id__in=posts_in_page)
            voted = voted.values_list('post_id', flat=True)
            context["voted"] = voted
        return context  

在html中我做

    {% for post in posts %}
<form method="post" action="{% url 'vote' %}" class="vote_form">
  <li> [{{ post.votes }}]
    {{post}}
    {% csrf_token %}
    <input type="hidden" id="id_post" name="post" class="hidden_id" value="{{ post.pk }}" />
    <input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" />
    {% if not user.is_authenticated %}
    <button disabled title="Please login to vote">+</button>
    {% elif post.pk not in voted %}
    <button>+</button>
    {% else %}
    <button>-</button>
    {% endif %}
      </form>
{% endform%}

【问题讨论】:

  • 你没有在return super(PostVoteCountManager, self).get_queryset.annotate(..)调用get_queryset,应该是return super(PostVoteCountManager, self).get_queryset().annotate(...)

标签: python django


【解决方案1】:

你把函数写成get_query_set,但名字是get_queryset [Django-doc]。此外,您忘记在此处调用get_queryset(..) 函数:

class PostVoteCountManager(models.Manager):

    def get_queryset(self):
        return super(PostVoteCountManager, self).get_queryset().annotate(
            votes=Count('vote')).order_by("-votes")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多