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

3๐Ÿ‘

โœ…

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)

๐Ÿ‘คCharlesthk

2๐Ÿ‘

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.

Leave a comment