Skip to content

Commit

Permalink
Top products plugin should now work! Missing tests, and probably some…
Browse files Browse the repository at this point in the history
… cleanup
  • Loading branch information
chrisglass committed May 7, 2011
1 parent eadf19e commit 4f96706
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
27 changes: 24 additions & 3 deletions cmsplugin_shop/cms_plugins.py
Expand Up @@ -5,6 +5,7 @@
from shop.models.productmodel import Product
from shop.models.ordermodel import OrderItem
from models import TopProducts
from django.db.models import Count

class CartCMSPlugin(CMSPluginBase):
model = CMSPlugin
Expand Down Expand Up @@ -33,10 +34,30 @@ class TopProductsPlugin(CMSPluginBase):
render_template = "top_products/plugins/top_products.html"

def render(self, context, instance, placeholder):
OrderItem.objects.all().group_by('product_reference')
context.update({
"""This is the main rendering function. We "simply" query the database
to get the top N products (as defined in the plugin instance), and pass
them to the context"""

top_products_data = OrderItem.objects.values(
'product_reference').annotate(
product_count=Count('product_reference')).order_by('product_count')[:instance.number_of_products]

# The top_products_data result should be in the form:
# [{'product_reference': '<product_id>', 'product_count': <count>}, ...]

top_products_list = []
for values in top_products_data:
prod = Product.objects.get(pk=values.get('product_reference'))
count = volues.get('product_count')
top_products_list.append({'object': prod, 'count' : count})

# TODO: Cache top_products_list, invalidate on new order (or just
# periodically maybe, it's not critical). Should be cached per
# instance.number_of_products, obviously.

context.update({
'instance': instance,
'products': instance.products.all(),
'products': top_products_list,
'placeholder': placeholder,
})
return context
Expand Down
3 changes: 3 additions & 0 deletions cmsplugin_shop/templates/cmsplugin_shop/top_products.html
@@ -0,0 +1,3 @@
{% for product in products %}
{{product.object.name}}
{% endfor %}

0 comments on commit 4f96706

Please sign in to comment.