Django - 如何在 col 中选择唯一值
我在 Django 上遇到了一个小问题,我无法解决。 假设我有这样的模型:
class Game(models.Model):
# some attributes here
class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
val = models.IntegerField()
#...
现在,我想将上一场比赛的所有得分保留在数据库中,但是当需要在页面上显示它们的值时,我只想为每场比赛中选定的玩家选择最佳得分。 我该怎么做?或者也许我必须改变分数模型?
I have a little problem with Django which I can't manage to solve.
Suppose that I have models like this:
class Game(models.Model):
# some attributes here
class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
val = models.IntegerField()
#...
Now, I want to keep in DB all the scores from last games, but when it comes to show their values on page I want to choose only the best score for chosen player in each game.
How do I do that? Or maybe I have to change Score model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我终于找到了解决方案。这与你们给我的完全不同,但谢谢你们所有人,因为它让我找到了答案的正确方法。您的答案仅返回一个,即玩家赢得的所有游戏中的最好成绩。每个游戏都与其他游戏不同,所以我必须保留它们。我的交易是为每场比赛给出最好的分数,并立即返回所有这些值。
我的解决方案做了我想要它做的事情:
I've finally found the solution. It's quite different from what you've given to me, but thanks for you all, because it turned my on right way to find the answer. You answers returns only one, the very best score of all the games player won. Each game is different from others so I have to keep them all. My deal was about to give best score for each game and return all these values at once.
My solution do, what I've wanted it to do:
根据您的 Django 版本,您可以执行以下操作:
Depending on your version of Django, you could do this:
为此,您可以使用 Django Max 函数
For this you can use the Django Max funciton
由于您正在尝试为显示执行此操作,因此我可能会将其放入 模板过滤器...
显然,您需要在那里进行一些错误检查。例如,您需要确保“分数”查询集实际上包含结果。
但是,您可以在模板中使用它,如下所示:
Since you are trying to do this for the display, I'd probably make it into a template filter...
You'd need some error checking in there, obviously. For instance, you'll want to make sure that the "scores" queryset actually has results in it.
But, then you can use it in a template like this: