(抱歉,如果英语不好)
我正在尝试按照Django的旧教程构建一个upvote系统。问题是,即使我尝试更新代码以保持其工作,它也会更改功能。这就是我所拥有的:
故事/ models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Story(models.Model):
title = models.CharField(max_length=255)
url = models.URLField()
points = models.IntegerField(default=1)
moderator = models.ForeignKey(User)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@property
def domain(self):
return urlparse(self.url).netloc
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "stories"
故事/ views.py
import datetime
from django.shortcuts import render
from django.utils.timezone import utc
from .models import Story
# Create your views here.
def score(story, gravity=1.8, timebase=120):
points = (story.points - 1)**0.8
now = datetime.datetime.utcnow().replace(tzinfo=utc)
age = int((now - story.created_at).total_seconds())/60
return points/(age+timebase)**1.8
def top_stories(top=180, consider=1000):
latest_stories = Story.objects.all().order_by('-created_at')[:consider]
ranked_stories = sorted([(score(story), story) for story in latest_stories], reverse=True)
return [story for _, story in ranked_stories][:top]
def index(request):
stories = top_stories(top=30)
return render(request, 'stories/index.html', {'stories': stories}
我遇到的问题是ranked_stories
,因为这样做的方式很旧。新版本使用lambda
,如this answer所示,但不起作用。
如果我使用
ranked_stories = sorted(latest_stories, key=lambda story: story.score(), reverse=True)
它返回:
>>'Story' object has no attribute 'score'
有没有办法让它发挥作用?