アクティブかどうかを定義するフィールドがいくつかある Coupon モデルと、ライブ クーポンのみを返すカスタム マネージャーがあります。クーポンにはアイテムへの FK があります。
Item のクエリで、利用可能な有効なクーポンの数に注釈を付けようとしています。ただし、カウント集計は、アクティブなクーポンだけでなく、すべてのクーポンをカウントしているようです。
# 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 構文に戻す変換は素晴らしいでしょう.