如何使用外键加入链接的模型?

发布于 2025-02-12 04:20:18 字数 795 浏览 0 评论 0原文

我来自Java,新来的Python / Django。所以我的问题可能是愚蠢的...

我有一个班级父母,其中包含与班级孩子的联系。

class Parent(models.Model):
    pass
    
class Child(models.Model):
    value = models.DecimalField(decimal_places=2, max_digits=12,default=0.0);
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE, null=True, related_name='children')

父母通过相关名称“孩子”提到其“孩子”。 在运行时,它运行良好,但是在设计时间,从班级父母的声明中无法实现。

如果我希望父母获得其子女的总结价值,我发现最好的选择是首先要找孩子,然后从中总结一下,

class Parent(models.Model):
@property
def total_value(self):
    return float(Child.objects.filter(parent=self).aggregate(Sum('value'))['value__sum']) or 0.00
pass

您知道是否有更好的方法可以做到这一点?我们无法想象类似的事情:

children.aggregate(Sum('value'))

换句话说:是否可以在不进行查询的情况下直接从父母(在设计时间)访问孩子?

I'm coming from Java and new to python / django. So may be my question is silly ...

I have one class Parent which contains an association with a class Child.

class Parent(models.Model):
    pass
    
class Child(models.Model):
    value = models.DecimalField(decimal_places=2, max_digits=12,default=0.0);
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE, null=True, related_name='children')

Parent refers to its 'Childs' through the related name 'children'.
At Run time it works well, but at design time, it isn't reachable from the declaration of the class Parent.

If I want the parent to get a summarized value of its children, the best option I found is to first get the set of children and then to summarize from it

class Parent(models.Model):
@property
def total_value(self):
    return float(Child.objects.filter(parent=self).aggregate(Sum('value'))['value__sum']) or 0.00
pass

Do you know if there is a better way to do this? Can't we imagine something like:

children.aggregate(Sum('value'))

In other words: is it possible to directly access the children from the Parent (at design time) without making a query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

寒江雪… 2025-02-19 04:20:18

您始终可以以相同的方式对待这两个:

Child.objects.filter(parent=self)
self.children.all()

但是首先您必须有一些parent对象。 parent的班级方法 self ,否则是这样的:

parent = Parent.objects.get(id=1)
parent.children.all()

因此,基本上应该有效:

self.children.aggregate(Sum('value'))['value__sum']

You can always treat the same way this two:

Child.objects.filter(parent=self)
self.children.all()

But first you have to have some Parent object. Inside class' methods of Parent it's self, otherwise it's something like:

parent = Parent.objects.get(id=1)
parent.children.all()

So basically this should work:

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