fair_ladyz
fair_ladyz

Reputation:

about annotate django

I'd like to create the top five best seller of the products in each month.

I've heard that the annotations must be used for this case but I don't know how to use it.

Will anybody be kind enough to help me ??

Upvotes: 2

Views: 5792

Answers (2)

dar
dar

Reputation: 6530

annotate is not the only way to do it. You could also use an extra aggregation, though it might not be very efficient, and this will rely on sql specific to your database. This approach will not work in App Engine, but should in a SQL compliant database.

For example, say you had a Product model and a SalesOrder model, where the SalesOrder model has a line item for each product_id and order_date in it.

top_products = Product.objects.extra( 
    select={'num_orders':'select count(product_id) from app_product where app_salesorder.order_date > thirty_days_ago and app_product.id = app_salesorder.product_id'})
        .order_by('-num_orders')[:5]

Upvotes: 5

vezult
vezult

Reputation: 5243

You need to provide much more information before anyone can provide you with a useful answer. Describe what you know, what you've tried, elaborate on what you hope to accomplish.

In the mean time, you can learn about django's annotate() function, and see a few examples by reading the aggregation documentation for django.

Upvotes: 7

Related Questions