#models.py
class Orders(models.Model):
orderid = models.IntegerField(db_column='orderID', primary_key=True)
pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True)
pickupstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='pickupStore', blank=True, null=True,related_name = 'pickupstore')
class Branch(models.Model):
branchid = models.IntegerField(db_column='branchID', primary_key=True) # Field name made lowercase.
city = models.CharField(max_length=45, blank=True, null=True)
“订单类”模型中的“取货店”字段是指“分支类”模型。
我想计算任何给定月份内所有商店(分支机构)的提货数量,包括当特定月份商店(分支机构)的提货数量为0时
这是我计算所有商店数量或提货的解决方案(2006年1月为分支机构,但是其中不包括订单数为0的商店
branchs = Orders.objects.all().select_related('pickupstore').values('pickupstore__city').filter(pickupdate__year = 2006, pickupdate__month = 1).annotate(num=Count('pickupstore__city')).order_by('pickupstore__city')
branchs = branchs.values('pickupstore__city').filter(pickupdate__year = year, pickupdate__month = month)
branchs = branchs.annotate(num=Count('pickupstore__city')).order_by('pickupstore__city')
答案 0 :(得分:0)
尝试先注释(),然后对其进行过滤:
pickup_branch = Orders.objects.all().select_related('pickupstore').annotate(num=Count('pickupstore__city')).values('pickupstore__city').filter(pickupdate__year = 2006, pickupdate__month = 1).order_by('pickupstore__city')
如果它不起作用,请尝试以下操作:
all_branch = Orders.objects.all().select_related('pickupstore')
pickup_branch = Orders.objects.all().select_related('pickupstore').values('pickupstore__city').filter(pickupdate__year = 2006, pickupdate__month = 1).annotate(num=Count('pickupstore__city')).order_by('pickupstore__city')
zero_pickup_branch = [branch for branch in all_branch if not branch in pickup_branch]
这将为您提供0个皮卡的分支
那么您只需将这些值设置为0。
答案 1 :(得分:0)
您需要将过滤器基于“分支”,因为您想要所有分支,甚至那些没有任何顺序的分支,因此需要左外部联接。有几种方法可以执行此操作,但是对于您而言,以下方法将起作用。
2 2018-07-24 16:40:00
3 2018-07-24 16:45:00
4 2018-07-24 16:50:00
5 2018-07-24 16:55:00
6 2018-07-24 18:00:00
Name: DateTime, dtype: datetime64[ns]