Django 模型聚合
我有一个简单的层次结构模型,其中一个 Person 和 RunningScore 作为子项。 该模型存储有关许多用户的跑步分数的数据,简化如下:
class Person(models.Model):
firstName = models.CharField(max_length=200)
lastName = models.CharField(max_length=200)
class RunningScore(models.Model):
person = models.ForeignKey('Person', related_name="scores")
time = models.DecimalField(max_digits=6, decimal_places=2)
如果我得到一个人,它会附带与其关联的所有跑步分数,这是标准行为。我的问题非常简单:如果我想得到一个只有 RunningScore 孩子的 Person(假设有更好的结果,又名 min(time) )我该怎么办? 我阅读了 Django 官方文档,但没有找到 解决方案。
I have a simple hierarchic model whit a Person and RunningScore as child.
this model store data about running score of many user, simplified something like:
class Person(models.Model):
firstName = models.CharField(max_length=200)
lastName = models.CharField(max_length=200)
class RunningScore(models.Model):
person = models.ForeignKey('Person', related_name="scores")
time = models.DecimalField(max_digits=6, decimal_places=2)
If I get a single Person it cames with all RunningScores associated to it, and this is standard behavior. My question is really simple: if I'd like to get a Person with only a RunningScore child (suppose the better result, aka min(time) ) how can I do?
I read the official Django documentation but have not found a
solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不是 100% 确定我是否明白您的意思,但也许这会有所帮助:
查询集将使用
min_running_time
附加属性获取 Person 对象。您还可以添加过滤器:
访问第一个对象的
min_running_time
属性:编辑:
您可以定义如下方法或属性来获取相关对象:
I am not 100% sure if I get what you mean, but maybe this will help:
The queryset will fetch Person objects with
min_running_time
additional attribute.You can also add a filter:
Accessing the first object's
min_running_time
attribute:EDIT:
You can define a method or a property such as the following one to get the related object:
如果您只想为一个人提供一个 RunningScore,您可以使用排序并将查询集限制为 1 个对象。
像这样的事情:
这是关于限制查询集的文档:
https: //docs.djangoproject.com/en/1.3/topics/db/queries/#limiting-querysets
If you want one RunningScore for only one Person you could use odering and limit your queryset to 1 object.
Something like this:
Here is the doc on limiting querysets:
https://docs.djangoproject.com/en/1.3/topics/db/queries/#limiting-querysets