如何将此查询转换为“django模型查询”?

时间:2010-03-28 17:46:12

标签: mysql django models

我想要的很简单:

模特:


class userLastTrophy(models.Model):
   user     = models.ForeignKey(userInfo)
   platinum = models.IntegerField()
   gold    = models.IntegerField()
   silver  = models.IntegerField()
   bronze  = models.IntegerField()
   level   = models.IntegerField()
   rank    = models.IntegerField()
   perc_level = models.IntegerField()
   date_update = models.DateTimeField(default=datetime.now, blank=True)
   total   = models.IntegerField()
   points  = models.IntegerField()

class userTrophy(models.Model):
   user     = models.ForeignKey(userInfo)
   platinum = models.IntegerField()
   gold    = models.IntegerField()
   silver  = models.IntegerField()
   bronze  = models.IntegerField()
   total   = models.IntegerField()
   level   = models.IntegerField()
   perc_level  = models.IntegerField()
   date_update = models.DateTimeField(default=datetime.now, blank=True)
   rank    = models.IntegerField(default=0)
   total   = models.IntegerField(default=0)
   points  = models.IntegerField(default=0)
   last_trophy = models.ForeignKey(userLastTrophy, default=0)

我有这个问题:


select t2.user_id as id,
       t2.platinum - t1.platinum as plat,
       t2.gold     - t1.gold as gold,
       t2.silver   - t1.silver as silver,
       t2.bronze   - t1.bronze as bronze,
       t2.points   - t1.points as points from myps3t_usertrophy t2, myps3t_userlasttrophy t1 where
       t1.id = t2.last_trophy_id order by points;

如何用django模型做到这一点?

1 个答案:

答案 0 :(得分:0)

只需创建一个带有日期字段的模型:

from django.contrib.auth.models import User

class Trophy(models.Model):
   user     = models.ForeignKey(User, related_name='trophies')
   creation_date = model.DateField(auto_now_add=True)

你会注意到:

  • 我们将外键设置为用户模型,而不是userinfo。通过这种方式,您可以轻松地获取当前用户及其在视图中的特洛伊。使UserInfo成为user profile
  • 奖杯的第一个字母大写。除非你获得了比用户更多的奖杯,否则用户前缀是无用的。
  • 创建日期,auto_now_add设置为true,将自动设置为创建新对象时的当前日期
  • 相关名称允许您为反向naturel提供自然名称,而不是获取'trophy_set'

然后你可以通过这种方式获得所有最后的奖杯:

# we get the last 3 trophies, '-' sort from last to first
print user.trophies.order_by('-creation_date')[:3]