This should do it:
total_bags = ShipmentBagSealMapping.objects.filter(shipment_id__time__range = [start_time,end_time],status='close').values('bag_seal').distinct().count()
See you have defined the field as shipment_id
not shipments
Frage
I've 2 models
class ShipmentBagSealMapping(models.Model):
bag_seal = models.CharField(max_length = 255)
status = models.CharField(max_length = 255, default = 'open')
time = models.DateTimeField( auto_now_add = True, db_index = True)
shipment_id = models.ForeignKey('Shipment', related_name = 'bags')
class Shipment(models.Model):
job_id = models.CharField(max_length = 255)
time = models.DateTimeField( auto_now_add = True, db_index = True)
I want to write a JOIN query which tells me the count of records in ShipmentBagSealMapping
with status = close
and time of Shipment
is in range [start_time and end_time]
.
Here' what I tried:
total_bags = ShipmentBagSealMapping.objects.filter(shipments__time__range = [start_time,end_time],status='close').values('bag_seal').distinct().count()
But it throws an error saying :-
Cannot resolve keyword 'shipments' into field. Choices are: bag_seal, id, shipment_id, status, time
How do I do it?
Lösung
This should do it:
total_bags = ShipmentBagSealMapping.objects.filter(shipment_id__time__range = [start_time,end_time],status='close').values('bag_seal').distinct().count()
See you have defined the field as shipment_id
not shipments
Andere Tipps
Django will automatically add _id in your ForeignKey, so make some change like this may help
class ShipmentBagSealMapping(model.Model):
bag_seal = models.CharField(max_length = 255)
status = models.CharField(max_length = 255 )
time = models.DateTimeField( auto_now_add = True)
shipments = models.ForeignKey('Shipment', related_name = 'bags')