From 4f15b820a5d19174fd03a248a8429a5206427ff0 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 17 Jun 2019 21:36:09 +0200 Subject: [PATCH] Use manager from queryset --- bda/admin.py | 2 +- bda/models.py | 12 +++++++----- bda/views.py | 10 ++++++---- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/bda/admin.py b/bda/admin.py index 18c712f8..7f626c7a 100644 --- a/bda/admin.py +++ b/bda/admin.py @@ -117,7 +117,7 @@ class ParticipantAdmin(ReadOnlyMixin, admin.ModelAdmin): inlines = [WithListingAttributionInline, WithoutListingAttributionInline] def get_queryset(self, request): - return self.model.objects_paid.get_queryset().annotate( + return self.model.objects.annotate_paid().annotate( nb_places=Count("attributions"), remain=Sum( "attribution__spectacle__price", filter=Q(attribution__paid=False) diff --git a/bda/models.py b/bda/models.py index de87731e..cee2c3e1 100644 --- a/bda/models.py +++ b/bda/models.py @@ -170,17 +170,20 @@ class Attribution(models.Model): ) -class ParticipantPaidManager(models.Manager): +class ParticipantPaidQueryset(models.QuerySet): """ Un manager qui annote le queryset avec un champ `paid`, indiquant si un participant a payé toutes ses attributions. """ - def get_queryset(self): + # OuterRef permet de se référer à un champ d'un modèle non encore fixé + # Voir: + # https://docs.djangoproject.com/en/2.2/ref/models/expressions/#django.db.models.OuterRef + def annotate_paid(self): unpaid = Attribution.objects.filter( participant=models.OuterRef("pk"), paid=False ) - return super().get_queryset().annotate(paid=~Exists(unpaid)) + return self.annotate(paid=~Exists(unpaid)) class Participant(models.Model): @@ -196,8 +199,7 @@ class Participant(models.Model): Spectacle, related_name="subscribed", blank=True ) - objects = models.Manager() - objects_paid = ParticipantPaidManager() + objects = ParticipantPaidQueryset.as_manager() def __str__(self): return "%s - %s" % (self.user, self.tirage.title) diff --git a/bda/views.py b/bda/views.py index 40595cbf..6a0e7ec7 100644 --- a/bda/views.py +++ b/bda/views.py @@ -378,7 +378,7 @@ def revente_manage(request, tirage_id): - Annulation d'une revente après que le tirage a eu lieu """ tirage = get_object_or_404(Tirage, id=tirage_id) - participant, created = Participant.objects_paid.get_or_create( + participant, created = Participant.annotate_paid().get_or_create( user=request.user, tirage=tirage ) @@ -734,9 +734,11 @@ class UnpaidParticipants(BuroRequiredMixin, ListView): template_name = "bda-unpaid.html" def get_queryset(self): - return Participant.objects_paid.filter( - tirage__id=self.kwargs["tirage_id"], paid=False - ).select_related("user") + return ( + Participant.objects.annotate_paid() + .filter(tirage__id=self.kwargs["tirage_id"], paid=False) + .select_related("user") + ) @buro_required