Django - 使用过滤器/排除功能不起作用

时间:2015-09-23 16:23:50

标签: django django-views

我有这段代码:

import datetime

today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)

pickingYesterday = Order.objects.exclude(actionorder__type__name = 'In process',actionorder__dateCreation__lt=today_min).filter(actionorder__type__name = 'Completed', actionorder__dateCreation__lt=today_min).count()

我想过滤掉这些条件适用的所有订单 昨天。

class Order(models.Model):

class Type(models.Model):
    name = models.CharField( max_length = 100)

class actionOrder(models.Model):
    order = models.ForeignKey(Order)
    Type = models.ForeignKey(Type)
    dateCreation  = models.DateTimeField( auto_now = True )

2 个答案:

答案 0 :(得分:0)

您可以通过以下方式获取昨天的日期:

from datetime import date, datetime, timedelta
today = date.today()
today = datetime(today.year, today.month, today.date)
yesterday = today - timedelta(days=1)

如果我理解正确,您希望订单操作的订单截至今日为“完整”,但昨天不是“完整”,对吧?如果是这样,你可以这样做:

pickingYesterday = Order.objects.filter(actionorder__type__name='Completed', 
                                        actionorder__dateCreation__gte=today) \
                                .exclude(actionorder__type__name='Completed', 
                                         actionorder__dateCreation__lte=today, 
                                         actionorder__dateCreation__gte=yesterday).count()

答案 1 :(得分:0)

看看我尝试这个并运作,意见?

from django.db.models import Q
import datetime

today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)

pickingYesterday = Order.objects.filter(actionorder__type__name = 'Completed', actionorder__dateCreation__lt=today_min).filter(actionorder__type__name = 'In process',actionorder__dateCreation__gte=today_min).count()
pickingYesterday += Order.objects.filter(actionorder__type__name = 'Completed', actionorder__dateCreation__lt=today_min).filter(~Q(actionorder__type__name = 'In process')).count()