django如何使用外键注释

时间:2018-11-16 17:57:00

标签: python django orm

考虑简单的Django模型

class Journey(models.Model):
    vrn=models.CharField(max_length=200) # Vehicle Reg No
    kilo=models.FloatField()

class J_user(models.Model):
    jdi=models.ForeignKey(Journey, related_name="Journey_User",on_delete = models.DO_NOTHING,)
    uid=models.IntegerField()

很容易在一个表中进行注释,就像我们想要每辆车的行驶总里程(vrn代表车辆的注册号)

Journey.objects.values('vrn').annotate(Total_kilo=Sum('kilo'))

现在,我想查询一个查询,该查询将返回每个用户在每辆汽车中行驶了多少公里。

“旅程数据表”

enter image description here

J_user表的数据

enter image description here

那么结果应该是

enter image description here

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

这是您的查询:

Journey
.objects
.order_by()   #<-- important to avoid include sort fields
.values('vrn', 'j_user__uid', )
.annotate(Total_kilo=Sum('kilo'))

values上的字段将包含在聚合子句中。样本:

print(
    Material
    .objects
    .values( "uf_id", "uf__mp__id", )
    .annotate( Sum("total_social_per_c") )
    .query )

结果:

SELECT "material_material"."uf_id", 
       "ufs_uf"."mp_id", 
       Sum("material_material"."total_social_per_c") AS 
       "total_social_per_c__sum" 
FROM   "material_material" 
       INNER JOIN "ufs_uf" 
               ON ( "material_material"."uf_id" = "ufs_uf"."id" ) 
GROUP  BY "material_material"."uf_id", 
          "ufs_uf"."mp_id" 

答案 1 :(得分:0)

根据您的模型,它应该是:

topics = c.classify("what about ")
if "resources" in topics:
    print("yes")