我正在尝试建立一个简单的排名系统,我按“分数”和“ID”对科目进行排序。我最初通过在 SQL 中设置“rownum”变量并像这样调用“Rank”来构建这是 PHP:
public function rank() {
global $database;
$sql = "SET @rownum :=0";
$database->query($sql);
$sql = "SELECT rank FROM (
SELECT @rownum:=@rownum+1 AS rank, id, score
FROM subjects
ORDER BY score DESC, id ASC) AS derived_table
WHERE id = {$this->id}";
$result_set = $database->query($sql);
$row = $database->fetch_array($result_set);
return array_shift($row);
}
我可以从 Queryset 中对其进行索引,但我也没有弄清楚如何做到这一点。关于如何在 Django 中完成此任务的任何想法?
该模型:
class Subject(models.Model):
def __unicode__(self):
return self.name
def __str__(self):
return self.name
name = models.CharField(max_length=40)
score = models.IntegerField(default=0)
created = models.DateTimeField(default=datetime.datetime.now)
提前致谢!