]> git.ipfire.org Git - thirdparty/patchwork.git/commitdiff
REST: Allow filtering by both project ID and linkname v2.0.0-rc2
authorStephen Finucane <stephen@that.guru>
Thu, 18 May 2017 22:25:26 +0000 (23:25 +0100)
committerStephen Finucane <stephen@that.guru>
Thu, 18 May 2017 22:26:16 +0000 (23:26 +0100)
In hindsight, it's a bit odd that we would filter project by linkname by
everything else by ID. Simply support both.

Signed-off-by: Stephen Finucane <stephen@that.guru>
Fixes: e27b68a ("REST: Filter on Project.linkname - not Project.pk")
patchwork/api/filters.py

index 00efc9997711b6f1dd9e26df0094007dd6c6fe54..3dc215c0485fb5d3814bd73e07f3484de295e1b5 100644 (file)
@@ -41,10 +41,34 @@ class TimestampMixin(FilterSet):
     since = IsoDateTimeFilter(name='date', **{LOOKUP_FIELD: 'gte'})
 
 
+class ProjectChoiceField(ModelChoiceField):
+
+    def to_python(self, value):
+        if value in self.empty_values:
+            return None
+
+        try:
+            filters = {'pk': int(value)}
+        except ValueError:
+            filters = {'name__iexact': ' '.join(value.split('-'))}
+
+        try:
+            value = self.queryset.get(**filters)
+        except (ValueError, TypeError, self.queryset.model.DoesNotExist):
+            raise ValidationError(self.error_messages['invalid_choice'],
+                                  code='invalid_choice')
+        return value
+
+
+class ProjectFilter(ModelChoiceFilter):
+
+    field_class = ProjectChoiceField
+
+
 class ProjectMixin(FilterSet):
 
-    project = ModelChoiceFilter(to_field_name='linkname',
-                                queryset=Project.objects.all())
+    project = ProjectFilter(to_field_name='linkname',
+                            queryset=Project.objects.all())
 
 
 class SeriesFilter(ProjectMixin, TimestampMixin, FilterSet):