Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rf#197 Rm prepare_data from context #627

Merged
merged 6 commits into from
Nov 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ ua-parser==0.8.0
user-agents==1.1.0
sorl-thumbnail==12.4a1
https://github.com/selwin/django-user_agents/archive/master.zip
https://github.com/fidals/refarm-site/archive/0.4.11.zip
https://github.com/fidals/refarm-site/archive/0.4.12.zip
32 changes: 32 additions & 0 deletions shopelectro/context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import typing

from catalog.context import AbstractProductsListContext
from catalog.models import ProductQuerySet
from images.models import Image


class ProductImages(AbstractProductsListContext):

@property
def images(self) -> typing.Dict[int, Image]:
Copy link
Contributor

@ArtemijRodionov ArtemijRodionov Nov 2, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is better to be a method, because it perform heavily computations

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@artemiy312 , we already have tags, products, product_pages in the same property-style.
Let's leave as is too keep it's style. And fidals/refarm-site#194 with it's subtasks will solve this problem too

assert isinstance(self.products, ProductQuerySet)

images = {}
if self.product_pages:
images = Image.objects.get_main_images_by_pages(
self.product_pages.filter(shopelectro_product__in=self.products)
)

return {
product.id: images.get(product.page)
for product in self.products
}

def get_context_data(self):
return {
'product_images': self.images,
**(
self.super.get_context_data()
if self.super else {}
),
}
18 changes: 1 addition & 17 deletions shopelectro/tests/tests_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
from django.urls import reverse
from django.utils.translation import ugettext as _

from catalog import context

from shopelectro import models
from shopelectro.views.service import generate_md5_for_ya_kassa, YANDEX_REQUEST_PARAM
from shopelectro.tests.helpers import create_doubled_tag
Expand Down Expand Up @@ -77,20 +75,6 @@ def get_category_page(
))


class CatalogPage(BaseCatalogTestCase):

def test_merge_product_cache(self):
"""Context merging should cached."""
products = models.Product.objects.all()[:2]
product_pages = models.ProductPage.objects.all()
with self.assertNumQueries(1):
# N db queries without before cached
context.prepare_tile_products(products, product_pages)
with self.assertNumQueries(0):
# no db queries after cached
context.prepare_tile_products(products, product_pages)


class CatalogTags(BaseCatalogTestCase):

def test_category_page_contains_all_tags(self):
Expand Down Expand Up @@ -258,7 +242,7 @@ def test_pagination_step(self):
"""Category page contains `pagination_step` count of products in list."""
pagination_step = 25
response = self.get_category_page(query_string={'step': pagination_step})
self.assertEqual(len(response.context['products_data']), pagination_step)
self.assertEqual(len(response.context['products']), pagination_step)

def test_pagination_404(self):
"""Category page returns 404 for a nonexistent page number."""
Expand Down
68 changes: 30 additions & 38 deletions shopelectro/views/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from catalog.views import catalog
from pages import views as pages_views

from shopelectro import context as se_context
from shopelectro import models
from shopelectro.views.helpers import set_csrf_cookie

Expand Down Expand Up @@ -70,24 +71,21 @@ def get_context_data(self, **kwargs):
**context_,
'price_bounds': settings.PRICE_BOUNDS,
'group_tags_pairs': self.product.get_params(),
'product_images': self.get_images_context().get_context_data()['product_images'],
'tile_products': context.prepare_tile_products(
self.product.get_siblings(offset=settings.PRODUCT_SIBLINGS_COUNT),
models.ProductPage.objects.all()
),
'product_images': self.get_images_context_data()['product_images'],
'tile_products': self.product.get_siblings(offset=settings.PRODUCT_SIBLINGS_COUNT),
}

def get_images_context(self):
def get_images_context_data(self) -> dict:
return (
context.ProductImages(
se_context.ProductImages(
url_kwargs={},
request=self.request,
page=self.product.page,
products=models.Product.objects.filter(id=self.product.id),
product_pages=models.ProductPage.objects.filter(
shopelectro_product=self.product
),
)
).get_context_data()
)

def render_siblings_on_404(
Expand All @@ -103,18 +101,15 @@ def render_siblings_on_404(
self.object = inactive_product
context_ = self.get_context_data(
object=inactive_product,
tile_products=context.prepare_tile_products(
inactive_product.get_siblings(
offset=settings.PRODUCT_SIBLINGS_COUNT
),
models.ProductPage.objects.all()
tile_products=inactive_product.get_siblings(
offset=settings.PRODUCT_SIBLINGS_COUNT
),
tile_title='Возможно вас заинтересуют похожие товары:',
**url_kwargs,
)

context_['product_images'] = (
self.get_images_context().get_context_data()['product_images']
self.get_images_context_data()['product_images']
)
return render(request, 'catalog/product_404.html', context_, status=404)

Expand All @@ -136,32 +131,29 @@ def get_context_data(self, **kwargs):
.select_related('page')
)
if not mobile_view:
tile_products = context.prepare_tile_products(
top_products,
models.ProductPage.objects.all()
)
tile_products = top_products

return {
**context_,
'tile_title': 'ТОП 10 ТОВАРОВ',
'category_tile': settings.MAIN_PAGE_TILE,
'tile_products': tile_products,
'product_images': (
self
.get_images_context(products=top_products)
.get_context_data()['product_images']
self.get_products_context_data(
products=top_products
)['product_images']
)
}

def get_images_context(self, products=None, product_pages=None):
def get_products_context_data(self, products=None, product_pages=None) -> dict:
return (
context.ProductImages(
se_context.ProductImages(
url_kwargs={}, # Ignore CPDBear
request=self.request,
page=self.object,
products=products or models.Product.objects.all(),
product_pages=product_pages or models.ProductPage.objects.all(),
)
).get_context_data()
)


Expand All @@ -176,12 +168,13 @@ def get_context_data(self, **kwargs):
request=self.request,
page=self.object,
products=models.Product.objects.all(),
product_pages=models.ProductPage.objects.all(),
product_pages=models.ProductPage.objects.all(), # Ignore CPDBear
)
| context.TaggedCategory(tags=models.Tag.objects.all())
| context.SortingCategory() # requires TaggedCategory
| context.PaginationCategory() # requires SortingCategory
| context.ProductImages()
| context.ProductBrands() # requires TaggedCategory
| se_context.ProductImages()
| context.DBTemplate() # requires TaggedCategory
)
return {
Expand Down Expand Up @@ -244,7 +237,7 @@ def load_more(request, category_slug, offset=0, limit=0, sorting=0, tags=None):
products = paginated_page.object_list
view = request.session.get('view_type', 'tile')

context_ = (
data_from_context = (
context.Category(
url_kwargs={},
request=request,
Expand All @@ -254,19 +247,18 @@ def load_more(request, category_slug, offset=0, limit=0, sorting=0, tags=None):
shopelectro_product__in=products
),
)
| context.ProductImages(
products=products,
product_pages=models.ProductPage.objects.filter(
shopelectro_product__in=products
)
)
)
| context.TaggedCategory(tags=models.Tag.objects.all())
| context.SortingCategory() # requires TaggedCategory
| context.PaginationCategory() # requires SortingCategory
| context.ProductBrands() # requires TaggedCategory
| se_context.ProductImages()
| context.DBTemplate() # requires TaggedCategory
).get_context_data()

return render(request, 'catalog/category_products.html', {
'products_data': context.prepare_tile_products(
products, models.ProductPage.objects.all()
),
'product_images': context_.get_context_data()['product_images'],
'products': products,
'product_images': data_from_context['product_images'],
'product_brands': data_from_context['product_brands'],
'paginated': paginated,
'paginated_page': paginated_page,
'view_type': view,
Expand Down
18 changes: 10 additions & 8 deletions templates/catalog/category_products.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
{% load se_extras %}
{% load user_agents %}

{% for product, brand in products_data %}
{% for product in products %}
<div class="product-card col-xs-6 col-md-4" data-product-id="{{ product.id }}"
itemscope itemtype="https://schema.org/Product">
<meta property="name" itemprop="name" content="{{ product.name }}">
Expand Down Expand Up @@ -40,14 +40,16 @@
<div class="js-order order row">
<input class="col-xs-4 input-number category-prods-count js-product-count js-touchspin"
type="number" value="1">
<button class="btn btn-blue btn-category-buy js-product-to-cart"
data-product-id="{{ product.id }}" data-product-price="{{ product.price }}"
data-product-name="{{ product.name }}"
data-product-brand="{% if brand %}{{ brand.name }}{% endif %}">
Купить
</button>
{% with brand=product_brands|get_item:product.id %}
<button class="btn btn-blue btn-category-buy js-product-to-cart"
data-product-id="{{ product.id }}" data-product-price="{{ product.price }}"
data-product-name="{{ product.name }}"
data-product-brand="{% if brand %}{{ brand.name }}{% endif %}">
Купить
</button>
{% endwith %}
</div>
</div>
</div>
{% endfor %}
<div class="hidden js-products-loaded">{{ products_data|length }}</div>
<div class="hidden js-products-loaded">{{ products|length }}</div>
3 changes: 1 addition & 2 deletions templates/layout/tile_products.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
{% if tile_products %}
<div itemscope itemtype="https://schema.org/Product" class="stuff-top">
<p class="stuff-top-title text-center">{{ tile_title }}</p>
{% for product, root_category in tile_products %}
{% for product in tile_products %}
<p class="hidden" itemprop="description">
{% with description=product.page.display_description %}
{% if description %}
Expand All @@ -30,7 +30,6 @@
{{ product.name }}
</a>
</div>
<div class="stuff-top-category">{{ root_category.name }}</div>
<div itemprop="offers" itemscope itemtype="https://schema.org/Offer" class="stuff-top-price-new">
<link itemprop="availability" href="https://schema.org/InStock">
<meta itemprop="description" content="{{ product.page.display_description }}">
Expand Down