我有2个模特
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)
我想写一个 JOIN 查询,它告诉我ShipmentBagSealMapping
中status = close
的记录数和Shipment
的时间范围{{1 }}
这里'我尝试过:
[start_time and end_time]
但它引发了一个错误说: -
total_bags = ShipmentBagSealMapping.objects.filter(shipments__time__range = [start_time,end_time],status='close').values('bag_seal').distinct().count()
我该怎么做?
答案 0 :(得分:0)
这应该这样做:
total_bags = ShipmentBagSealMapping.objects.filter(shipment_id__time__range = [start_time,end_time],status='close').values('bag_seal').distinct().count()
看到您已将该字段定义为shipment_id
而非shipments
答案 1 :(得分:0)
Django会自动在你的ForeignKey中添加_id,所以做一些像这样的改变可能有帮助
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')