41

Django新手问题:)

我有以下模型 - 每个评论都是针对一个产品的,每个产品都有一个部门:

class Department(models.Model):
    code = models.CharField(max_length=16)
class Product(models.Model):
    id = models.CharField(max_length=40, primary_key=True, db_index=True)
    dept = models.ForeignKey(Department, null=True, blank=True, db_index=True)
class Review(models.Model):
    review_id = models.CharField(max_length=32, primary_key=True, db_index=True) 
    product = models.ForeignKey(Product, db_index=True) 
    time = models.DateTimeField(db_index=True) 

我想对日期范围(2012-01-01 到 2012-01-08)进行 Django 查询,并返回所有部门的列表,用部门 ID 进行注释,以及该部门审查的产品数量在该日期范围内。

这让我的大脑有点煎熬:)

我可以获得一个时间范围内的所有评论:

 reviews = Review.filter(time__range=["2012-01-01", "2012-01-08"])

然后我猜每个评论都有一个产品领域,每个产品都有一个部门代码。但是我如何按产品和代码、计数和部门 ID 对它们进行分组?

或者,是否最好请求部门,然后以某种方式用产品数量对它们进行注释?

4

5 回答 5

43

extra尽可能避免raw聚合文档几乎有这个用例:

直接来自文档:

# Each publisher, each with a count of books as a "num_books" attribute.
>>> from django.db.models import Count
>>> pubs = Publisher.objects.annotate(num_books=Count('book'))
>>> pubs
[<Publisher BaloneyPress>, <Publisher SalamiPress>, ...]
>>> pubs[0].num_books
73

因此,要针对您的特定示例进行修改:

depts = Department.objects.
            filter(product__review__time__range=["2012-01-01", "2012-01-08"]).
            annotate(num_products=Count('product'))

单独行上的函数调用只是为了便于阅读,您应该相应地移动它们。我没有对此进行测试,但我认为它应该可以工作。

于 2012-07-11T02:54:10.310 回答
7

在 django>= 2.0中,这可以通过

depts = Department.objects.all().annotate(
    num_products=Count('product', filter=Q(product__review__time__range=["2012-01-01", "2012-01-08"]))
)

有关更多信息,请阅读文档https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#filtering-on-annotations

于 2019-03-15T04:28:22.297 回答
5

在过去的几天里,我不得不做几个类似的查询,最简单的方法是使用extraqueryset 函数用过滤后的产品计数来注释查询集中的每个对象:

start = ..  # need to be formatted correctly
end = ...
departments = Departments.objects.all().extra(select = {
     'product_count' : """ SELECT COUNT(*) FROM appname_department
                           JOIN appname_product
                               ON appname_product.dept_id = appname_department.id
                           JOIN appname_review 
                               ON appname_review.product_id = appname_product.id
                           WHERE appname_review.time BETWEEN %s AND %s
                       """
}, params=[start, end])

{% for department in departments %}
    {{ department.product_count }}
{% endfor %}
于 2012-07-11T01:26:39.713 回答
0

聚合文档 https://docs.djangoproject.com/en/dev/topics/db/aggregation/#cheat-sheet

可能有一种使用聚合或注释的方法,但我更喜欢这个:

departments = Department.objects.all()
for dept in departments : 
    # Get the number of reviewed products for a given range and department
    num_products = dept.product_set.filter(review__time__range=["2012-01-01", "2012-01-08"]).count()

如果您绝对需要它作为模型的功能:

class Department(models.Model) :
    ...
    def num_products(self, start_date, end_date) : 
        return self.product_set.filter(review__time__range=[start_date, end_date]).count()

编辑

我认为如果您要进行原始查询(类似这样)

sql = """SELECT COUNT(Product.*) as num_products, Department.*
    FROM Department
    LEFT OUTER JOIN Product ON Product.department = Department.id
    LEFT OUTER JOIN Review ON Product.id = Review.product
    WHERE Review.time BETWEEN "2012-01-01" AND "2012-01-08"
    GROUP BY Department.id"""

Department.objects.raw(sql)

然后 num_products 将成为结果中每个 Dept 实例的属性。

您可能需要稍微使用字段+表名

于 2012-07-10T17:34:19.647 回答
0

我有类似的数据模型相同的情况。

我的解决方案是:

 Department.objects \
.extra(where=["<review_table_name.time_field> BETWEEN <time1> AND <time2> "])\
.annotate(num_products=Count('product__review__product_id'))
于 2015-10-07T14:48:52.567 回答