我有3个型号: -
class Shipment(models.Model):
job_id = models.CharField(max_length = 255)
time = models.DateTimeField(auto_now = True, auto_now_add = True, db_index = True)
class ShipmentBagSealMapping(models.Model):
bag_seal = models.CharField(max_length = 255)
status = models.CharField(max_length = 255, default = 'open')
time = models.DateTimeField(auto_now = True, auto_now_add = True, db_index = True)
shipment_id = models.ForeignKey('Shipment', related_name = 'bags')
class ShipmentPPTLMapping(models.Model):
pptl_id = models.CharField(max_length = 255)
time = models.DateTimeField(auto_now = True, auto_now_add = True)
shipment_id = models.ForeignKey('Shipment', related_name = 'pptls')
我想获取已关闭的行李的数量。
最初我有pptl_id
。因此,我从shipment_id
模型获取ShipmentPPTLMapping
,然后使用ShipmentBagSealMapping
查询shipmen_id
模型。
以下是我所做的: -
bags_closed = len(Shipment.objects.filter(bags_ status _exact ='close',bags_ time _range = [start_time,end_time],pptls__pptl_id__exact = pptls.pptl_id ))
问题是因为每个包都可以有多个货物,因此根据我的查询,我能够得到所有关闭货物的数量。我想添加另一个过滤,例如bags_value = distinct
类似
bags_closed = len(Shipment.objects.filter(bags__status__exact = 'close', bags__time__range = [start_time,end_time],pptls__pptl_id__exact = 147)).**bags_seal = distinct**
问题2
另外,我需要获取last_bagged_on
参数,该参数为我提供了最后一个关闭的行李的时间。显然,此字段将从ShipmentBagSealMapping
模型中获取,但我当前的对象是模型Shipment
。
如何关闭最后一个包?
这样的事情: -
last_bagged_on = Shipment.objects.filter(bags__status__exact = 'close', bags__time__range = [start_time,end_time],pptls__pptl_id__exact = pptls.pptl_id)[0].**bags_time**
答案 0 :(得分:1)
len(queryset)是一种计算对象的坏方法。请改用.count()
bags_closed = Shipment.objects.filter(bags__status__exact='close',
bags__time__range=[start_time,end_time],
pptls__pptl_id__exact = 147)\
.distinct('bags').count()
last_bagged_on = ShipmentBagSealMapping.objects.filter(
status__exact='close',
time__range=[start_time,end_time],
shipment_id__pptls__pptl_id__exact=pptls.pptl_id)[0]
如果你正在使用Django 1.6,你应该使用last_bagged_on = ShipmentBagSealMapping ... first()而不是[0]