Browse Source

Allow filtering on item availability

Jocelyn Delande 9 years ago
parent
commit
c6dbc049b4
2 changed files with 35 additions and 1 deletions
  1. 22 1
      hardware_provisioning/admin.py
  2. 13 0
      hardware_provisioning/models.py

+ 22 - 1
hardware_provisioning/admin.py

@@ -31,12 +31,33 @@ class OwnerFilter(admin.SimpleListFilter):
             return queryset
 
 
+class AvailabilityFilter(admin.SimpleListFilter):
+    title = "Disponibilité"
+    parameter_name = 'availability'
+
+    def lookups(self, request, model_admin):
+        return [
+            ('available', 'Disponible'),
+            ('borrowed', 'Emprunté'),
+        ]
+
+    def queryset(self, request, queryset):
+        if self.value() == 'available':
+            return queryset.available()
+        elif self.value() == 'borrowed':
+            return queryset.borrowed()
+        else:
+            return queryset
+
+
 @admin.register(Item)
 class ItemAdmin(admin.ModelAdmin):
     list_display = (
         'designation', 'type', 'mac_address', 'serial', 'owner',
         'buy_date', 'is_available')
-    list_filter = ('type__name', 'storage', 'buy_date', OwnerFilter)
+    list_filter = (
+        AvailabilityFilter, 'type__name', 'storage',
+        'buy_date', OwnerFilter)
     search_fields = (
         'designation', 'mac_address', 'serial',
         'owner__email', 'owner__nickname',

+ 13 - 0
hardware_provisioning/models.py

@@ -18,6 +18,17 @@ class ItemType(models.Model):
         verbose_name_plural = 'types d’objet'
 
 
+class ItemQuerySet(models.QuerySet):
+    def _get_borrowed_pks(self):
+        return Loan.objects.running().values_list('item', flat=True)
+
+    def available(self):
+        return self.exclude(pk__in=self._get_borrowed_pks())
+
+    def borrowed(self):
+        return self.filter(pk__in=self._get_borrowed_pks())
+
+
 class Item(models.Model):
     type = models.ForeignKey(ItemType, verbose_name='type de matériel',
                              related_name='items')
@@ -45,6 +56,8 @@ class Item(models.Model):
     comment = models.TextField(verbose_name='commentaire', blank=True,
                                null=True)
 
+    objects = ItemQuerySet().as_manager()
+
     def __unicode__(self):
         return self.designation