Code

Ticket #3520: manager.diff

File manager.diff, 1.2 KB (added by Simon Litchfield <simon@…>, 7 years ago)
Line 
1--- django/db/models/manager.py  Sat Feb 17 15:52:02 2007
2+++ django/db/models/manager.py  Sat Feb 17 15:51:52 2007
3@@ -84,6 +84,23 @@
4     def complex_filter(self, *args, **kwargs):
5         return self.get_query_set().complex_filter(*args, **kwargs)
6
7+    def search_filter(self, lookups, data, **kwargs):
8+        """Runs filter using field lookups and values from supplied dicts.
9+        For example, running search_filter with --
10+            lookups = {'myfield': 'myfield', 'mytext': 'mytext__startswith', 'mydate': 'mydata__lte'}
11+            data = {'myfield': 'somevalue', 'mytext': 'h', 'mydate': ''}
12+        Would be the same as --
13+            filter(myfield='somevalue', mytext__startswith='h')
14+        Skips empty values. Useful for searching against form or request data.
15+        """
16+        sf_args = {}
17+        for item in lookups:
18+            if data.has_key(item):
19+                if data[item] != '' and data[item] != None:
20+                    sf_args[lookups[item]] = data[item]
21+        sf_args.update(kwargs)
22+        return self.get_query_set().filter(**sf_args)
23+
24     def exclude(self, *args, **kwargs):
25         return self.get_query_set().exclude(*args, **kwargs)