daily pastebin goal
2%
SHARE
TWEET

Untitled

a guest Feb 19th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class JSONTextFieldFilter(Filter):
  2.     json_field_name = ""
  3.     choices = {}
  4.  
  5.     def __init__(self, json_field_name=None, choices=None, **kwargs):
  6.         self.choices = choices if choices else {}
  7.         self.json_field_name = json_field_name if json_field_name else ""
  8.         super().__init__(**kwargs)
  9.  
  10.     def modify_value(self, value):
  11.         value = json.dumps({self.json_field_name: self.choices.get(value.lower(), value)})
  12.         return value[1:-1]  # remove first '{' character and last - '}'
  13.  
  14.     def filter(self, qs, value):
  15.         if isinstance(value, Lookup):
  16.             lookup = six.text_type(value.lookup_type)
  17.             value = value.value
  18.         else:
  19.             lookup = self.lookup_expr
  20.         if value in EMPTY_VALUES:
  21.             return qs
  22.  
  23.         value = self.modify_value(value)
  24.         qs = self.get_method(qs)(**{'%s__%s' % (self.field_name, lookup): value})
  25.  
  26.         if self.distinct:
  27.             qs = qs.distinct()
  28.  
  29.         return qs
  30.  
  31.  
  32. class RelatedJSONTextFieldFilter(JSONTextFieldFilter):
  33.     related_field_name = None
  34.  
  35.     def __init__(self, related_field_name=None, **kwargs):
  36.         self.related_field_name = related_field_name
  37.         super().__init__(**kwargs)
  38.  
  39.     def filter(self, qs, value):
  40.         if isinstance(value, Lookup):
  41.             lookup = six.text_type(value.lookup_type)
  42.             value = value.value
  43.         else:
  44.             lookup = self.lookup_expr
  45.  
  46.         value = self.modify_value(value)
  47.  
  48.         qs = qs.prefetch_related(self.field_name).filter(
  49.             **{'%s__%s__%s' % (self.field_name, self.related_field_name, lookup): value})
  50.  
  51.         if self.distinct:
  52.             qs = qs.distinct()
  53.  
  54.         return qs
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top