从django的关系表中获取价值和总和

时间:2017-10-19 19:43:31

标签: python django django-models

我在python django上有两个模块(类),如下例所示:

#first one
class Names(models.Model):
    name = models.CharField(max_length=200)
    type = models.ForeignKey(Types)
    value = models.IntegerField()

#second one
class Type(models.Model):
    name = models.CharField(max_length=200)

如您所见,班级Names与班级Type有关系,因此如何制定公式以获取每个班级type中的姓名总数和值的总和得到这样的结果,例如:

type1_total_names = 4
type1_sum_val = 22

2 个答案:

答案 0 :(得分:1)

以下内容将汇总类型数据和值的数据。您可以在 spring: jpa: mapping-resources: - db/mappings/dummy.xml

中找到总和
sum_value

答案 1 :(得分:0)

query the related objects,您可以尝试以下代码:

WITH professionals as (
    INSERT INTO professionals(id, company_id, first_name) 
    VALUES (1, 1, 'peter') RETURNING *
), 
services as (
    INSERT INTO services(id, professional_id, name) 
    VALUES (1, (select professionals.id from professionals), 'haircut')
)
INSERT INTO features(id, professional_id, name) 
VALUES (1, (select professionals.id from professionals), 'autobook');

select * from professionals;
select * from services;
select * from features;