使用Django中的Querysets编写SQL连接查询

时间:2013-12-10 09:41:19

标签: sql django

我正在尝试使用django Queryset在两个表上编写连接查询,因此需要编写建议  使用Django中的Querysets进行SQL连接查询..

这是我的查询和表格模型

   SELECT t.time, d.id2
   FROM  disp_b_time t JOIN disp_dispatch d ON t.id1 = d.id2
   WHERE  t.status = "completed" AND d.status = 0  AND d.vehicle_id =1 

class B_Time(models.Model):
    id1 =  models.ForeignKey(Book)
    dispatcher= models.ForeignKey(D)
    status = models.CharField(max_length=128, choices=B_STATUS)
    time = models.DateTimeField(auto_now=True, auto_now_add=True)
    register = models.DateField()
    modified = models.DateTimeField(auto_now=True, auto_now_add=True)


class Dispatch(models.Model):
    id2 = models.ForeignKey(Book)
    vehicle = models.ForeignKey(Vehicle)
    driveId = models.ForeignKey(Drive)
    dispId  = models.ForeignKey(D)
    status = models.CharField(max_length=128, choices=STATUS)
    register = models.DateTimeField()
    modified = models.DateTimeField(auto_now=True, auto_now_add=True)   

提前致谢...

2 个答案:

答案 0 :(得分:0)

d = Dipatch.objects.filter(vehicle__pk=1)\
                   .filter(status=0).filter(dispID__b_time__status='completed')

答案 1 :(得分:0)

为什么

d = Dipatch.objects.filter(vehicle__pk=1)\
                   .filter(status=0).filter(dispID__b_time__status='completed')

我们可以简单地将其写为

d = Dipatch.objects.filter(vehicle__pk=1, status=0, dispID__b_time__status='completed')