Django:确定用户是否投票

时间:2010-05-13 20:00:32

标签: python sql django orm

我有一长串链接,我使用下面的代码,总投票,提交,通常的东西吐出但我不是100%如何确定当前登录的用户是否已在链接上投票或不。我知道如何在我的视图中执行此操作,但是我是否需要更改下面的视图代码,还是可以使用模板的工作方式来确定它?

我已阅读Django Vote Up/Down method但我不太明白发生了什么(并且不需要任何新闻)。

模型(摘录):

class Link(models.Model):
    category = models.ForeignKey(Category, blank=False, default=1)
    user = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    url = models.URLField(max_length=1024, unique=True, verify_exists=True)
    name = models.CharField(max_length=512)

    def __unicode__(self):
        return u'%s (%s)' % (self.name, self.url)

class Vote(models.Model):
    link = models.ForeignKey(Link)
    user = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return u'%s vote for %s' % (self.user, self.link)

观点(摘录):

def hot(request):
    links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created')
    for link in links:
        delta_in_hours = (int(datetime.now().strftime("%s")) - int(link.created.strftime("%s"))) / 3600
        link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5)
        if request.user.is_authenticated():
            try:
                link.voted = Vote.objects.get(link=link, user=request.user)
            except Vote.DoesNotExist:
                link.voted = None

    links = sorted(links, key=lambda x: x.popularity, reverse=True)

    links = paginate(request, links, 15)

    return direct_to_template(
        request,
        template = 'links/link_list.html',
        extra_context = {
            'links': links,
        })

上述观点实际上实现了我的需要,但我认为这是一种非常低效的方式。这导致了可怕的n + 1个查询,因为它代表了对包含29个链接的页面的33个查询,而最初我只有4个查询。我真的更喜欢使用Django的ORM或至少.extra()。

有什么建议吗?

修改

@Gabriel Hurley

我正在尝试重新创建你的答案,我的结果好坏参半,让我告诉你我得到了什么。

views.py

links = Link.objects.select_related().extra(
    select={
        'votes': 'COUNT(links_vote.id)',
        'voted': 'SELECT COUNT(links_vote.id) FROM links_vote WHERE links_vote.user_id = 1 AND links_vote.link_id = links_link.id',
    },
    tables = ['links_vote']
)

models.py

class Vote(models.Model):
    link = models.ForeignKey(Link)
    user = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('link', 'user')

    def __unicode__(self):
        return u'%s vote for %s' % (self.user, self.link)

但是它返回了一个错误:

subquery uses ungrouped column "links_link.id" from outer query

第1行:... E links_vote.user_id = 1 AND links_vote.link_id = links_link ...

生成的查询看起来像(完全)这样:

SELECT (SELECT COUNT(links_vote.id) FROM links_vote WHERE links_vote.user_id = 1 AND links_vote.link_id = links_link.id) AS "voted", "links_link"."id", "links_link"."category_id", "links_link"."user_id", "links_link"."created", "links_link"."modified", "links_link"."url", "links_link"."name", "links_category"."id", "links_category"."name", "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "links_link" INNER JOIN "links_category" ON ("links_link"."category_id" = "links_category"."id") INNER JOIN "auth_user" ON ("links_link"."user_id" = "auth_user"."id") , "links_vote"

我正在使用PostgreSQL,我知道喜欢GROUP BY,但我不是100%就如何纠正这个问题。

编辑2(重大进展)

links = Link.objects.select_related()。annotate(votes = Count('vote'))。extra(     选择= {         #'voteed':'SELECT COUNT()FROM links_vote WHERE links_vote.user_id =%s AND links_vote.link_id = links_link.id'%(request.user.id),         #'voteed':''%(request.user.id),         #'voteed':'SELECT CASE WHEN links_vote.user_id =%s THEN 1 ELSE 0 END'%(request.user.id),         #'voteed':'SELECT COUNT()FROM links_vote WHERE links_vote.link_id = links_link.id AND links_vote.user_id =%s'%(request.user.id),     },     where = ['links_link.id = links_vote.link_id'], ).order_by( ' - 创建')

*这仅适用于从此处(http://code.djangoproject.com/ticket/11916

应用错误修补程序后

我非常接近于找到我需要确定用户是否投票的最后一篇文章......

1 个答案:

答案 0 :(得分:2)

之前我已经解决了这个问题,并且extra或多或少地解决了这个问题:

# annotate whether you've already voted on this item
table = Vote._meta.db_table
select = 'SELECT COUNT(id) FROM %s' %table
where1 = 'WHERE ' + table + '.user_id = %s'
where2 = 'AND ' + table + '.item_id = appname_item.id'
items = items.extra(
        select={'votes':" ".join((select, where1, where2,))},
        select_params=(request.user.id,)
    )

实际上,这将获取项目的QuerySet,并使用0或一些投票数注释每个项目。在我的系统中,我在投票上使用unique_together = ('link', 'user')来确保每个用户只能投票一次,因此带注释的数据是0或1(实际上是布尔值)。它运作良好,避免了n + 1问题。