如何在django模型中查询特定的外部记录

时间:2018-06-18 22:32:58

标签: django django-models

鉴于这些模型:

wp_die

我希望能够拥有一个仅包含今天“添加”的Vmt记录的结果集。

我试过这个:

class Cluster(models.Model):
    name = models.TextField()


class Vmt(models.Model):
    added = models.DateField(default=datetime.date.today, blank=True, null=True)
    purpose = models.TextField(blank=True, null=True)
    status = models.TextField(blank=True, null=True)
    cluster = models.ForeignKey(Cluster, null=True)


    class Meta:
        unique_together = (("cluster", "added"),)

但我得到的结果如下:

for c in Cluster.objects.filter(vmt__added='2018-06-18'):
    print "%s Vmt count = %s" % (c.name, c.vmt_set.count())
    for vmt in c.vmt_set.all():
        print "vmt added %s" % (vmt.added)

我希望:

GL-AURM24 Vmt count = 2
vmt added 2018-06-18
vmt added 2018-06-17
GL-AURM23 Vmt count = 2
vmt added 2018-06-18
vmt added 2018-06-17
JCK-AURM10 Vmt count = 2
vmt added 2018-06-18
vmt added 2018-06-17

这个SQL产生我想要的结果:

GL-AURM24 Vmt count = 1
vmt added 2018-06-18
GL-AURM23 Vmt count = 1
vmt added 2018-06-18
JCK-AURM10 Vmt count = 1
vmt added 2018-06-18

如何在Django查询中编写SQL?

1 个答案:

答案 0 :(得分:0)

对于Cluster.objects.filter中的c(vmt__added ='2018-06-18'):     打印“%s Vmt count =%s”%(c.name,c.vmt_set.filter(vmt__added ='2018-06-18')。count())     对于c.vmt_set.filter中的vmt(vmt__added ='2018-06-18'):         打印“添加了vmt%s”%(添加了vmt。)

Cluster.objects.filter(vmt__added ='2018-06-18')

返回至少添加了一个vmt的所有群集2018-06-18

c.vmt_set.all()

返回所有与c相关的vmt。这是一个新查询。