Login

query builder

Author:
cristianpsycho
Posted:
January 26, 2017
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

""" Takes arguments & constructs Qs for filter() We make sure we don't construct empty filters that would return too many results We return an empty dict if we have no filters so we can still return an empty response from the view """

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def dynamic_query(model, fields, types, values, operator):
    """
     Takes arguments & constructs Qs for filter()
     We make sure we don't construct empty filters that would return too many results
     We return an empty dict if we have no filters so we can still return an empty response from the view
    """
    queries = []
    for (f, t, v) in zip(fields, types, values):
        # We only want to build a Q with a value
        if v != "":
            kwargs = {str('%s__%s' % (f, t)): str('%s' % v)}
            queries.append(Q(**kwargs))

    # Make sure we have a list of filters
    if len(queries) > 0:
        q = Q()
        # AND/OR awareness
        for query in queries:
            if operator == "and":
                q = q & query
            elif operator == "or":
                q = q | query
            else:
                q = None
        if q:
            # We have a Q object, return the QuerySet
            return model.objects.filter(q)
    else:
        # Return an empty result
        return {}

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

arthur (on January 26, 2017):

You can use model.objects.none() in place of {}.

#

Please login first before commenting.