[Answer]-Optimizing the Django-SQL Query

1👍

At first correct your models, foreign key’s field names should not contains _id in end. That will cause many problems and disappointments later

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)

Second

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

This should solve your question

Leave a comment