首页 > Django的Count()

Django的Count()

我现在知道Django.db.models.Count()可以根据所给的关联字段返回被关联 model 的数量,那么它可不可以返回被关联model中符合某种条件的数量呢?
比如

class Cate(model.Model):
    name = models.CharField();
class Product(model.Model):
    cate = models.ForeignKey(Cate);
    isnew = models.BooleanField();    

查询所有分类的同时返回分类下的产品数量可以:

Cate.objects.annotate(num_pro=Count('cate'))

但是如果要查询所有分类下产品isnew为true的产品数量应该怎么做呢?谢谢指教!


方法比较low,试试是否可以。Product.objects.filter(cate__in = Cate.objects.filter(product__isnew=True).distinct())


问题解决了,没有用到Count(),用了extra

Cate.objects.extra(select={'num_pro': 'select count(*) from appname_product where isnew=True'})

但是这样写总感觉不舒服,而且文档里也说由于手写sql不容易保障在不同数据库之间保证兼容所以应该尽量少用这个extra,希望能找到比这更好的办法。


更low的方法,不用count,用len()。。。

【热门文章】
【热门文章】