Created
February 22, 2016 21:05
-
-
Save SmithWebster/3f09bd011c5de1112558 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import unicode_literals | |
from django.db import models | |
# Create your models here. | |
class Category(models.Model): | |
name = models.CharField('Группа товара', max_length=64) | |
def __unicode__(self): | |
return self.name | |
class Product(models.Model): | |
category = models.ForeignKey(Category, verbose_name='Группа') | |
name = models.CharField('Название товара', max_length=128) | |
price = models.DecimalField('Стоимость единицы, руб.', max_digits=10, decimal_places=2) | |
def __unicode__(self): | |
return self.name + " (" + str(self.price) + ")" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.shortcuts import render | |
from django.http import HttpResponse | |
from django.db.models import Count | |
from project.main.models import * | |
# Create your views here. | |
def home(request): | |
products = Product.objects.filter(price__gte=100).values() | |
categories = Category.objects.values('id', 'name')\ | |
.annotate(count=Count('product__id'))\ | |
.filter(count__gt=10) # where more than 10 products | |
categoryProducts = {} | |
for product in products: | |
catId = product['category_id'] | |
if not catId in categoryProducts: | |
categoryProducts[catId] = [] | |
categoryProducts[catId].append(product) | |
tree = [] | |
for category in categories: | |
catItem = { | |
'category_id': category['id'], | |
'name': category['name'], | |
'productsCount': category['count'], | |
'products': categoryProducts[category['id']], | |
} | |
tree.append(catItem) | |
return HttpResponse(tree) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment