Django 模型聚合

发布于 2024-11-14 08:20:42 字数 536 浏览 5 评论 0原文

我有一个简单的层次结构模型,其中一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对不⑦ 2024-11-21 08:20:42

我不是 100% 确定我是否明白您的意思,但也许这会有所帮助:

from django.db.models import Min
Person.objects.annotate(min_running_time=Min('time'))

查询集将使用 min_running_time 附加属性获取 Person 对象。

您还可以添加过滤器:

Person.objects.annotate(min_running_time=Min('time')).filter(firstName__startswith='foo')

访问第一个对象的 min_running_time 属性:

first_person = Person.objects.annotate(min_running_score=Min('time'))[0]
print first_person.min_running_time

编辑:

您可以定义如下方法或属性来获取相关对象:

class Person(models.Model):
...
    @property
    def best_runner(self):
        try:
            return self.runningscore_set.order_by('time')[0]
        except IndexError:
            return None

I am not 100% sure if I get what you mean, but maybe this will help:

from django.db.models import Min
Person.objects.annotate(min_running_time=Min('time'))

The queryset will fetch Person objects with min_running_time additional attribute.

You can also add a filter:

Person.objects.annotate(min_running_time=Min('time')).filter(firstName__startswith='foo')

Accessing the first object's min_running_time attribute:

first_person = Person.objects.annotate(min_running_score=Min('time'))[0]
print first_person.min_running_time

EDIT:

You can define a method or a property such as the following one to get the related object:

class Person(models.Model):
...
    @property
    def best_runner(self):
        try:
            return self.runningscore_set.order_by('time')[0]
        except IndexError:
            return None
债姬 2024-11-21 08:20:42

如果您只想为一个人提供一个 RunningScore,您可以使用排序并将查询集限制为 1 个对象。
像这样的事情:

Person.runningscore_set.order_by('-time')[0]

这是关于限制查询集的文档:

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:

Person.runningscore_set.order_by('-time')[0]

Here is the doc on limiting querysets:

https://docs.djangoproject.com/en/1.3/topics/db/queries/#limiting-querysets

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文