开发者

How to convert this query to a "django model query"?

开发者 https://www.devze.com 2022-12-24 05:05 出处:网络
What i want is simple : models : class userLastTrophy(models.Model): user= models.ForeignKey(userInfo) platinum = models.IntegerField()

What i want is simple :

models :


class userLastTrophy(models.Model):
   user     = models.ForeignKey(userInfo)
   platinum = models.IntegerField()
   gold    = models.IntegerField()
   silver  = models.IntegerField()
   bronze  = models.Inte开发者_JAVA百科gerField()
   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)

I have this query :


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;

how to do this with django models ?


Just make it one model with a field for the date is has been created:

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)

You'll notice that:

  • we set the foreign key to a user model, not userinfo. This way you can get the current user and it's trohys in a view easily. make UserInfo a user profile
  • Trophy should have its first letter uppercase. And the user prefix is pretty useless unless you got trophy for something else than users.
  • creation date, with auto_now_add set to true, will be automatically set to the current date when the new object will be created
  • related name allow you to give a natural name to the reverse naturel instead of getting 'trophy_set'

You can then got all the last trophies this way:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号