What are the best ways to make your website faster such that it loads up faster and consumes less data in django

Viewed 266

Currently I am working on a django website. I had two queries about speeding up my website.

  1. I have a products page in which I display products. Currently when I tested it with 15 pics each sizing around 8-10mb the page took too much time to load. What should be the appropriate size of the image such that it follows the above conditions and also the image quality does not get very bad.

2)I am having a page where all the products are displayed of all categories and its view look like below

qs = Product.objects.select_related('category').order_by(*sorting)
    types = [
        (k, list(vs))
        for k, vs in groupby(qs, attrgetter('category'))
    ]

I wanted to know will having different pages for different categories will help to load the site faster by filtering the products such as p=Product.objects.filter() . Or filtering would take the same time as to show all products in one single page?

2 Answers

1.1) To reduce image size, I highly recommend you to use django-imagekit which is the perfect tool to resize images on Django

1.2) Make sure your images are loaded with apporpriate caching headers (expires and CacheControl)

2.1) For your query, you can make the query from the Category model to avoid manually grouping your results:

# this retrieve categories and associated products
categories = Category.objects.all().prefetch_related('product_set')

And in your template :

{% for category in categories %}
    {{ category.name }}
    {% for product in category.product_set.all %}
        {{ product.name }}
    {% endfor %}
{% endfor %}

2.2) You can make use of the cache_page decorator to save your page in cache :

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def my_view(request):

2.3) Do not load all of your products (if there is a lot) at once. Use a pagination strategy or an infinite scroll strategy (with ajax)

I wanted to know will having different pages for different categories will help to load the site faster by filtering the products such as p=Product.objects.filter(). Or filtering would take the same time as to show all products in one single page?

Filtering will be normally be faster, and definitely on a field with an index, and a ForeignKey has an index.

If you thus now the id of the Category, you can simply filter with:

Product.objects.filter(category_id=id_of_category)

This will filter at the database side, which will thus result in fewer records being returned to the Django/Python layer, less processing, and less rendering.

Related