如何在Django模型中获得唯一值?

时间:2014-03-22 07:22:08

标签: python django django-models

我有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**

1 个答案:

答案 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]