optimize db requests on club sales view

This commit is contained in:
imperosol
2025-11-07 13:07:46 +01:00
parent 3b56d2c22b
commit 742ac504dc
4 changed files with 31 additions and 40 deletions

View File

@@ -6,11 +6,11 @@ because it works with a somewhat dynamic form,
but was written before Alpine was introduced in the project. but was written before Alpine was introduced in the project.
TODO : rewrite the pagination used in this template an Alpine one TODO : rewrite the pagination used in this template an Alpine one
#} #}
{% macro paginate(page_obj, paginator, js_action) %} {% macro paginate(page_obj, paginator) %}
{% set js = js_action|default('') %} {% set js = "formPagination(this)" %}
{% if page_obj.has_previous() or page_obj.has_next() %} {% if page_obj.has_previous() or page_obj.has_next() %}
{% if page_obj.has_previous() %} {% if page_obj.has_previous() %}
<a {% if js %} type="submit" onclick="{{ js }}" {% endif %} href="?page={{ page_obj.previous_page_number() }}">{% trans %}Previous{% endtrans %}</a> <a type="submit" onclick="{{ js }}" href="?page={{ page_obj.previous_page_number() }}">{% trans %}Previous{% endtrans %}</a>
{% else %} {% else %}
<span class="disabled">{% trans %}Previous{% endtrans %}</span> <span class="disabled">{% trans %}Previous{% endtrans %}</span>
{% endif %} {% endif %}
@@ -18,11 +18,11 @@ TODO : rewrite the pagination used in this template an Alpine one
{% if page_obj.number == i %} {% if page_obj.number == i %}
<span class="active">{{ i }} <span class="sr-only">({% trans %}current{% endtrans %})</span></span> <span class="active">{{ i }} <span class="sr-only">({% trans %}current{% endtrans %})</span></span>
{% else %} {% else %}
<a {% if js %} type="submit" onclick="{{ js }}" {% endif %} href="?page={{ i }}">{{ i }}</a> <a type="submit" onclick="{{ js }}" href="?page={{ i }}">{{ i }}</a>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
{% if page_obj.has_next() %} {% if page_obj.has_next() %}
<a {% if js %} type="submit" onclick="{{ js }}" {% endif %} href="?page={{ page_obj.next_page_number() }}">{% trans %}Next{% endtrans %}</a> <a type="submit" onclick="{{ js }}" href="?page={{ page_obj.next_page_number() }}">{% trans %}Next{% endtrans %}</a>
{% else %} {% else %}
<span class="disabled">{% trans %}Next{% endtrans %}</span> <span class="disabled">{% trans %}Next{% endtrans %}</span>
{% endif %} {% endif %}
@@ -81,6 +81,10 @@ TODO : rewrite the pagination used in this template an Alpine one
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
{{ paginate(paginated_result, paginator) }}
{% endblock %}
{% block script %}
<script type="text/javascript"> <script type="text/javascript">
function formPagination(link){ function formPagination(link){
const form = document.getElementById("form") const form = document.getElementById("form")
@@ -89,7 +93,6 @@ TODO : rewrite the pagination used in this template an Alpine one
form.submit(); form.submit();
} }
</script> </script>
{{ paginate(paginated_result, paginator, "formPagination(this)") }}
{% endblock %} {% endblock %}

View File

@@ -30,7 +30,7 @@ from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin from django.contrib.messages.views import SuccessMessageMixin
from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError
from django.core.paginator import InvalidPage, Paginator from django.core.paginator import InvalidPage, Paginator
from django.db.models import Q, Sum from django.db.models import F, Q, Sum
from django.http import Http404, HttpResponseRedirect, StreamingHttpResponse from django.http import Http404, HttpResponseRedirect, StreamingHttpResponse
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse, reverse_lazy from django.urls import reverse, reverse_lazy
@@ -370,7 +370,7 @@ class ClubOldMembersView(ClubTabsMixin, PermissionRequiredMixin, DetailView):
class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailFormView): class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailFormView):
"""Sellings of a club.""" """Sales of a club."""
model = Club model = Club
pk_url_kwarg = "club_id" pk_url_kwarg = "club_id"
@@ -396,9 +396,8 @@ class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailFormView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
kwargs = super().get_context_data(**kwargs) kwargs = super().get_context_data(**kwargs)
qs = Selling.objects.filter(club=self.object)
kwargs["result"] = qs[:0] kwargs["result"] = Selling.objects.none()
kwargs["paginated_result"] = kwargs["result"] kwargs["paginated_result"] = kwargs["result"]
kwargs["total"] = 0 kwargs["total"] = 0
kwargs["total_quantity"] = 0 kwargs["total_quantity"] = 0
@@ -406,6 +405,7 @@ class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailFormView):
form = self.get_form() form = self.get_form()
if form.is_valid(): if form.is_valid():
qs = Selling.objects.filter(club=self.object)
if not len([v for v in form.cleaned_data.values() if v is not None]): if not len([v for v in form.cleaned_data.values() if v is not None]):
qs = Selling.objects.none() qs = Selling.objects.none()
if form.cleaned_data["begin_date"]: if form.cleaned_data["begin_date"]:
@@ -425,18 +425,18 @@ class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailFormView):
if len(selected_products) > 0: if len(selected_products) > 0:
qs = qs.filter(product__in=selected_products) qs = qs.filter(product__in=selected_products)
kwargs["total"] = qs.annotate(
price=F("quantity") * F("unit_price")
).aggregate(total=Sum("price", default=0))["total"]
kwargs["result"] = qs.select_related( kwargs["result"] = qs.select_related(
"counter", "counter__club", "customer", "customer__user", "seller" "counter", "counter__club", "customer", "customer__user", "seller"
).order_by("-id") ).order_by("-id")
kwargs["total"] = sum([s.quantity * s.unit_price for s in kwargs["result"]]) kwargs["total_quantity"] = qs.aggregate(total=Sum("quantity", default=0))[
total_quantity = qs.all().aggregate(Sum("quantity")) "total"
if total_quantity["quantity__sum"]: ]
kwargs["total_quantity"] = total_quantity["quantity__sum"] kwargs["benefit"] = qs.exclude(product=None).aggregate(
benefit = ( res=Sum("product__purchase_price", default=0)
qs.exclude(product=None).all().aggregate(Sum("product__purchase_price")) )["res"]
)
if benefit["product__purchase_price__sum"]:
kwargs["benefit"] = benefit["product__purchase_price__sum"]
kwargs["paginator"] = Paginator(kwargs["result"], self.paginate_by) kwargs["paginator"] = Paginator(kwargs["result"], self.paginate_by)
try: try:

View File

@@ -153,7 +153,7 @@
current_page (django.core.paginator.Page): the current page object current_page (django.core.paginator.Page): the current page object
paginator (django.core.paginator.Paginator): the paginator object paginator (django.core.paginator.Paginator): the paginator object
#} #}
{{ paginate_server_side(current_page, paginator, False) }} {{ paginate_server_side(current_page, paginator, False) }}
{% endmacro %} {% endmacro %}
{% macro paginate_htmx(current_page, paginator) %} {% macro paginate_htmx(current_page, paginator) %}
@@ -168,7 +168,7 @@
current_page (django.core.paginator.Page): the current page object current_page (django.core.paginator.Page): the current page object
paginator (django.core.paginator.Paginator): the paginator object paginator (django.core.paginator.Paginator): the paginator object
#} #}
{{ paginate_server_side(current_page, paginator, True) }} {{ paginate_server_side(current_page, paginator, True) }}
{% endmacro %} {% endmacro %}
{% macro paginate_server_side(current_page, paginator, use_htmx) %} {% macro paginate_server_side(current_page, paginator, use_htmx) %}

View File

@@ -6,7 +6,7 @@
msgid "" msgid ""
msgstr "" msgstr ""
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-10-17 13:41+0200\n" "POT-Creation-Date: 2025-11-04 12:43+0100\n"
"PO-Revision-Date: 2016-07-18\n" "PO-Revision-Date: 2016-07-18\n"
"Last-Translator: Maréchal <thomas.girod@utbm.fr\n" "Last-Translator: Maréchal <thomas.girod@utbm.fr\n"
"Language-Team: AE info <ae.info@utbm.fr>\n" "Language-Team: AE info <ae.info@utbm.fr>\n"
@@ -893,7 +893,8 @@ msgstr "Administration des mailing listes"
msgid "Actions" msgid "Actions"
msgstr "Actions" msgstr "Actions"
#: com/templates/com/mailing_admin.jinja core/templates/core/file_detail.jinja #: com/templates/com/mailing_admin.jinja com/templates/com/poster_list.jinja
#: core/templates/core/file_detail.jinja
#: core/templates/core/file_moderation.jinja sas/templates/sas/moderation.jinja #: core/templates/core/file_moderation.jinja sas/templates/sas/moderation.jinja
#: sas/templates/sas/picture.jinja #: sas/templates/sas/picture.jinja
msgid "Moderate" msgid "Moderate"
@@ -1109,8 +1110,7 @@ msgstr "Vous n'avez pas accès à ce contenu"
msgid "Poster" msgid "Poster"
msgstr "Affiche" msgstr "Affiche"
#: com/templates/com/poster_edit.jinja com/templates/com/poster_moderate.jinja #: com/templates/com/poster_edit.jinja com/templates/com/screen_edit.jinja
#: com/templates/com/screen_edit.jinja
msgid "List" msgid "List"
msgstr "Liste" msgstr "Liste"
@@ -1123,25 +1123,13 @@ msgstr "Affiche - modifier"
msgid "Create" msgid "Create"
msgstr "Créer" msgstr "Créer"
#: com/templates/com/poster_list.jinja
msgid "Moderation"
msgstr "Modération"
#: com/templates/com/poster_list.jinja
msgid "No posters"
msgstr "Aucune affiche"
#: com/templates/com/poster_list.jinja com/templates/com/screen_slideshow.jinja #: com/templates/com/poster_list.jinja com/templates/com/screen_slideshow.jinja
msgid "Click to expand" msgid "Click to expand"
msgstr "Cliquez pour agrandir" msgstr "Cliquez pour agrandir"
#: com/templates/com/poster_moderate.jinja #: com/templates/com/poster_list.jinja
msgid "Posters - moderation" msgid "No posters"
msgstr "Affiches - modération" msgstr "Aucune affiche"
#: com/templates/com/poster_moderate.jinja
msgid "No objects"
msgstr "Aucun éléments"
#: com/templates/com/screen_edit.jinja #: com/templates/com/screen_edit.jinja
msgid "Screen" msgid "Screen"