优化Django-SQL查询

时间:2014-02-13 10:24:38

标签: mysql sql django

我有3个模特。

class ShipmentPPTLMapping(models.Model):
    pptl_id = models.CharField(max_length = 255)
    shipment_id = models.ForeignKey('Shipment', related_name = 'pptls')

class ShipmentBagSealMapping(models.Model):
    bag_seal = models.CharField(max_length = 255)
    status = models.CharField(max_length = 255, default = 'open')
    shipment_id = models.ForeignKey('Shipment', related_name = 'bags')



class Shipment(models.Model):
    job_id = models.CharField(max_length = 255)

我需要编写一个查询,根据from ShipmentBagSealMapping closed过滤pptl_id行李from ShipmentPPTLMapping的状态。

我一开始就有pptl_id。因此,我会过滤掉与此相关的所有货件,因为shipments_objShipmentBagSealMapping相关,因此使用shipments_obj是我可以过滤掉已关闭行李的唯一方式。

shipment_pptl_mapping_obj_list = ShipmentPPTLMapping.objects.filter(pptl_id = pptl_id)

然后我循环shipment_pptl_mapping_obj_list找到状态为closed的行李。

for shipment_pptl_mapping_obj in shipment_pptl_mapping_obj_list:
    closed_bags = shipment_pptl_mapping_obj.shipment_id.bags.filter(status = 'closed')
    #and then again another loop
    for bags in closed_bags:
        #something

如何在1个查询中找到所有内容?

这是我的最终代码

shipment_pptl_mapping_obj_list = ShipmentPPTLMapping.objects.filter(pptl_id = pptl_id)  #--> extend this
for shipment_pptl_mapping_obj in shipment_pptl_mapping_obj_list:
    closed_bags = shipment_pptl_mapping_obj.shipment_id.bags.filter(status = 'closed')
    for bags in closed_bags:
        #do something

我想要这样的东西

closed_bags = Some Query
for bags in closed_bags:
    #do_something

1 个答案:

答案 0 :(得分:1)

首先更正模型,外键的字段名称最后不应包含_id。这将导致许多问题和后来的失望

class ShipmentPPTLMapping(models.Model):
    pptl_id = models.IntegerField() # if you id is Integer of course
    shipment = models.ForeignKey('Shipment', related_name = 'pptls')

class ShipmentBagSealMapping(models.Model):
    bag_seal = models.CharField(max_length = 255)
    status = models.CharField(max_length = 255, default = 'open')
    shipment = models.ForeignKey('Shipment', related_name = 'bags')



class Shipment(models.Model):
    job_id = models.IntegerField(max_length = 255)

第二

closed_bags = Shipment.objects.filter(pptls__pptl_id__exact=pptl_id, status='closed')

这应该可以解决你的问题