我有一个优惠券模型,它有一些字段来定义它是否处于活动状态,以及一个只返回实时优惠券的自定义管理器。优惠券对物品有一个 FK。
在对 Item 的查询中,我试图注释可用的有效优惠券的数量。但是,Count 聚合似乎正在计算所有优惠券,而不仅仅是活动优惠券。
# models.py
class LiveCouponManager(models.Manager):
"""
Returns only coupons which are active, and the current
date is after the active_date (if specified) but before the valid_until
date (if specified).
"""
def get_query_set(self):
today = datetime.date.today()
passed_active_date = models.Q(active_date__lte=today) | models.Q(active_date=None)
not_expired = models.Q(valid_until__gte=today) | models.Q(valid_until=None)
return super(LiveCouponManager,self).get_query_set().filter(is_active=True).filter(passed_active_date, not_expired)
class Item(models.Model):
# irrelevant fields
class Coupon(models.Model):
item = models.ForeignKey(Item)
is_active = models.BooleanField(default=True)
active_date = models.DateField(blank=True, null=True)
valid_until = models.DateField(blank=True, null=True)
# more fields
live = LiveCouponManager() # defined first, should be default manager
# views.py
# this is the part that isn't working right
data = Item.objects.filter(q).distinct().annotate(num_coupons=Count('coupon', distinct=True))
和位有其他原因 - 查询是这样的.distinct()
,distinct=True
它将返回重复项。这一切都很好,只是为了完整起见在这里提到它。
问题在于Count
包含被自定义管理器过滤掉的非活动优惠券。
有什么方法可以指定Count
应该使用live
管理器吗?
编辑
以下 SQL 查询正是我所需要的:
SELECT data_item.title, COUNT(data_coupon.id) FROM data_item LEFT OUTER JOIN data_coupon ON (data_item.id=data_coupon.item_id)
WHERE (
(is_active='1') AND
(active_date <= current_timestamp OR active_date IS NULL) AND
(valid_until >= current_timestamp OR valid_until IS NULL)
)
GROUP BY data_item.title
至少在sqlite上。任何 SQL 大师的反馈都将不胜感激 - 我觉得我在这里编程是偶然的。或者,更好的是,翻译回 Django ORM 语法会很棒。