Python 在for循环之后,我又遇到了一点麻烦。我不能order\u by('popularity'),因为它在我的数据库中不是一个真实的字段,并且是动态计算的,所以我必须将我的queryset转换为一个对象列表,并从中排序popularity

Python 在for循环之后,我又遇到了一点麻烦。我不能order\u by('popularity'),因为它在我的数据库中不是一个真实的字段,并且是动态计算的,所以我必须将我的queryset转换为一个对象列表,并从中排序popularity,python,django,algorithm,postgresql,Python,Django,Algorithm,Postgresql,下一行只是我的分页器快捷方式,谢天谢地,分页不需要查询集,这与一些通用视图不同(与您交谈对象列表) 把所有东西都吐到一个很好的直接到模板的通用视图中,然后快快乐乐地走。这是一个非常好的主意。我从来没有想过这个网站会变得非常大,所以必须对这些数字进行一些重大调整,但我喜欢它的发展方向。虽然晚了几个月,但我又回来了。你不介意再详细解释一下吧?你如何记录你的跑步记录?另一个数据库表?是否会在每次Http请求时动态计算?不要担心否决票,我得出的结论是,在大多数情况下,否决票是个坏主意。buildingr

下一行只是我的分页器快捷方式,谢天谢地,分页不需要查询集,这与一些通用视图不同(与您交谈对象列表)


把所有东西都吐到一个很好的直接到模板的通用视图中,然后快快乐乐地走。

这是一个非常好的主意。我从来没有想过这个网站会变得非常大,所以必须对这些数字进行一些重大调整,但我喜欢它的发展方向。虽然晚了几个月,但我又回来了。你不介意再详细解释一下吧?你如何记录你的跑步记录?另一个数据库表?是否会在每次Http请求时动态计算?不要担心否决票,我得出的结论是,在大多数情况下,否决票是个坏主意。buildingreputation.com有一些很好的阅读。我真的认为这就是我想要的,尽管出于某种原因,我不断地得到相同的错误:在渲染时捕获异常:“karma_total”列不存在第1行:选择((karma_total-1)/POW(2,1.5))作为“受欢迎度”,(S…这很奇怪,因为我认为karma_total已经定义在它上面的一行了!如果你在最终结果中不需要它,那么就替换它:
“流行度”:(SUM(vote.karma_delta)-1)/POW(2,1.5)“
Man,这是我希望最有效的答案。其他答案都很好,但我希望这一个能起作用。渲染时发现一个异常:表“投票”第1行的子句条目中缺少:选择((vote.karma_total-1)/POW(2,1.5))作为“流行度…是我的最新错误。这与我使用1.1.1而不是开发版本没有任何关系,对吗?您的投票表不是通过选择相关添加到查询中的;您可以通过修改额外内容并添加
表=['vote']来手动添加它。”
如果您的投票表被调用
投票
查看我的编辑3代码。我离得太近了,我能尝到它!我遇到一个错误,因为我的分组中没有合适的值。考虑到django通常会处理这个问题,我不确定如何添加它们。这是否意味着每次投票链接时,每个人都会唱歌链接行被更新了?不…它只会更新投票的链接…所以它不会是处理器密集型的嗯,吃掉了很多HTML。啊,我不担心。作为旁注,有一种更简单的方法可以使用datetime.timedelta:(datetime.now()-link.created)。total_seconds()/3600以小时计算delta_ Y Combinator's Hacker News: Popularity = (p - 1) / (t + 2)^1.5` Votes divided by age factor. Where` p : votes (points) from users. t : time since submission in hours. p is subtracted by 1 to negate submitter's vote. Age factor is (time since submission in hours plus two) to the power of 1.5.factor is (time since submission in hours plus two) to the power of 1.5.
class Link(models.Model):
category = models.ForeignKey(Category)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
fame = models.PositiveIntegerField(default = 1)
title = models.CharField(max_length = 256)
url = models.URLField(max_length = 2048)

def __unicode__(self):
    return self.title

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

def __unicode__(self):
    return str(self.karma_delta)
def index(request):
popular_links = Link.objects.select_related().annotate(karma_total = Sum('vote__karma_delta'))
return render_to_response('links/index.html', {'links': popular_links})
from django.shortcuts import render_to_response
from linkett.apps.links.models import *

def index(request):
popular_links = Link.objects.select_related()
popular_links = popular_links.extra(
    select = {
        'karma_total': 'SUM(vote.karma_delta)',
        'popularity': '(karma_total - 1) / POW(2, 1.5)',
    },
    order_by = ['-popularity']
)
return render_to_response('links/index.html', {'links': popular_links})
Caught an exception while rendering: column "karma_total" does not exist
LINE 1: SELECT ((karma_total - 1) / POW(2, 1.5)) AS "popularity", (S...
TemplateSyntaxError: Caught an exception while rendering: missing FROM-clause entry for table "vote"
LINE 1: SELECT ((vote.karma_total - 1) / POW(2, 1.5)) AS "popularity...
{% block content %} {% for link in links %} karma-up {{ link.karma_total }} karma-down {{ link.title }} Posted by {{ link.user }} to {{ link.category }} at {{ link.created }}

{% empty %} No Links {% endfor %} {% endblock content %} from django.db.models import Sum from django.shortcuts import render_to_response from linkett.apps.links.models import *

def index(request): popular_links = Link.objects.select_related().extra( select = { 'popularity': '(SUM(links_vote.karma_delta) - 1) / POW(2, 1.5)', }, tables = ['links_link', 'links_vote'], order_by = ['-popularity'], ) return render_to_response('links/test.html', {'links': popular_links}) TemplateSyntaxError at / Caught an exception while rendering: column "links_link.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...karma_delta) - 1) / POW(2, 1.5)) AS "popularity", "links_lin...
popular_links = Link.objects.select_related()
popular_links = popular_links.extra(
    select = {
        'karma_total': 'SUM(vote.karma_delta)',
        'popularity': '(karma_total - 1) / POW(2, 1.5)'
    },
    order_by = ['-popularity']
)
from datetime import datetime, timedelta

class Link(models.Model):
 category = models.ForeignKey(Category)
 user = models.ForeignKey(User)
 created = models.DateTimeField(auto_now_add = True)
 modified = models.DateTimeField(auto_now = True)
 fame = models.PositiveIntegerField(default = 1)
 title = models.CharField(max_length = 256)
 url = models.URLField(max_length = 2048)

 #a field to keep the most recently calculated popularity
 popularity = models.FloatField(default = None)

 def CalculatePopularity(self):
  """
  Add a shorcut to make life easier ... this is used by the overloaded save() method and 
  can be used in a management function to do a mass-update periodically
  """
  ts = datetime.now()-self.created
  th = ts.seconds/60/60
  self.popularity = (self.user_set.count()-1)/((th+2)**1.5)

 def save(self, *args, **kwargs):
  """
  Modify the save function to calculate the popularity
  """
  self.CalculatePopularity()
  super(Link, self).save(*args, **kwargs)


 def __unicode__(self):
     return self.title

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

 def save(self, *args, **kwargs):
  """
  Modify the save function to calculate the popularity of the Link object
  """
  self.link.CalculatePopularity()
  super(Vote, self).save(*args, **kwargs)

 def __unicode__(self):
     return str(self.karma_delta)
from itertools import imap
imap(lambda x:x.CalculatePopularity(), Link.objects.all().select_related().iterator())
Link.objects.all().order_by('-popularity')
def hot(request):
    links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created')[:150]
    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)

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

    links = paginate(request, links, 5)

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