Skip to content

Instantly share code, notes, and snippets.

@jzmiller1
Created June 4, 2016 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jzmiller1/627071f555186cd1a58bb8f065205ff7 to your computer and use it in GitHub Desktop.
Save jzmiller1/627071f555186cd1a58bb8f065205ff7 to your computer and use it in GitHub Desktop.
Terrible Things
class UUIDIdMixin(models.Model):
class Meta:
abstract = True
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Body(UUIDIdMixin):
name = models.CharField(max_length=140)
description = models.CharField(max_length=280)
data = JSONField(blank=True, null=True)
def __str__(self):
return "Body {} - {}".format(self.pk, self.name)
class Crater(UUIDIdMixin):
TYPES = {'int': int,
'float': float,
'str': str}
body = models.ForeignKey(Body)
data = JSONField(blank=True, null=True)
class CratersFilter(django_filters.FilterSet):
data = django_filters.MethodFilter(action='filter_data')
class Meta:
model = models.Crater
fields = ['id', 'body']
def filter_data(self, queryset, value):
keys = value.split("~!@!~")
filters = [tuple(key.split(":")) for key in keys]
for f in filters:
if len(f) > 3:
field, field_type, value, lookup_type = f
else:
field, field_type, value = f
lookup_type = None
field_type = self.Meta.model.TYPES.get(field_type)
if field_type is not None:
value = field_type(value)
if lookup_type is not None:
query_arg = 'data__{}__{}'.format(field, lookup_type)
else:
query_arg = 'data__{}'.format(field)
del lookup_type
kwargs = {query_arg: value}
queryset = queryset.filter(**kwargs)
return queryset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment