Skip to content

Instantly share code, notes, and snippets.

@andres-torres-marroquin
Created December 11, 2013 14:41
Show Gist options
  • Save andres-torres-marroquin/7911510 to your computer and use it in GitHub Desktop.
Save andres-torres-marroquin/7911510 to your computer and use it in GitHub Desktop.
class CacheBooleanField(serializers.BooleanField):
EXPIRES = 3600 * 24 * 30
def field_from_native(self, data, files, field_name, into):
result = super(CacheBooleanField, self).field_from_native(
data, files, field_name, into
)
value = into.get(field_name, self.default)
cache.set(self.get_key(), value, self.EXPIRES)
return result
def get_key(self, obj=None):
request = self.context.get('request')
if request is None:
return
if obj is None:
obj = self.parent.object
class_name = self.parent.__class__.__name__
user_id = self.context.get('request').user.id
obj_id = obj.id
return '%s-%s-%s' % (class_name, obj_id, user_id)
def field_to_native(self, obj, field_name):
value = cache.get(self.get_key(obj), False)
return self.to_native(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment