如何使用外键加入链接的模型?
我来自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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您始终可以以相同的方式对待这两个:
但是首先您必须有一些
parent
对象。parent
的班级方法 self ,否则是这样的:因此,基本上应该有效:
You can always treat the same way this two:
But first you have to have some
Parent
object. Inside class' methods ofParent
it'sself
, otherwise it's something like:So basically this should work: