def get_prep_lookup(self, lookup_type, value):
if lookup_type in ('has_key', 'has_keys', 'has_any_keys'):
return value
return (Json(dict(value), dumps=json_serialiser)
if isinstance(value, dict)
else super().get_prep_lookup(lookup_type, value))
# def validate(self, value, model_instance):
# super(JSONField, self).validate(value, model_instance)
# try:
# json.dumps(dict(value))
# except TypeError:
# raise exceptions.ValidationError(
# self.error_messages['invalid'],
# code='invalid',
# params={'value': value},
# )
python类JSONField()的实例源码
def __init__(self, *args, **kwargs):
super(JSONAgg, self).__init__(*args, output_field=JSONField(), **kwargs)
def __init__(self, *args, **kwargs):
super(JSONBuildArray, self).__init__(*args, output_field=JSONField(), **kwargs)
def __init__(self, field, children=None):
expressions = []
for cfield, kids in (children or {}).items():
expressions.append(IncludeExpression(cfield, kids))
if isinstance(field, GenericRelation):
self._constructor = GenericRelationConstructor(field, expressions)
elif getattr(field, 'many_to_many', False):
self._constructor = ManyToManyConstructor(field, expressions)
elif getattr(field, 'multiple', False):
self._constructor = ManyToOneConstructor(field, expressions)
else:
self._constructor = IncludeExpressionConstructor(field, expressions)
super(IncludeExpression, self).__init__(output_field=JSONField())
def get_prep_value(self, value):
if value is not None:
return _JsonAdapter(value, encoder=self.encoder)
return value
# Django 1.11 and above can use the contrib JSONField as it supports
# the encoder kwarg, which means we can use DjangoJSONEncode; 1.10
# and 1.9 must use our hacked together version (which is a direct
# copy+paste from the 1.11 codebase).
def test_right_form_field_used(self):
from jsonfield_compat.util import django_supports_native_jsonfield, is_db_postgresql
if is_db_postgresql() and django_supports_native_jsonfield():
from jsonfield_compat.forms import JSONFormField
from django.contrib.postgres.fields import JSONField as _JSONFormField
self.assertTrue(JSONFormField is _JSONFormField)
else:
from jsonfield_compat.forms import JSONFormField
from jsonfield.forms import JSONFormField as _JSONFormField
self.assertTrue(JSONFormField is _JSONFormField)
def test_use_jsonfield_form_field(self):
with self.settings(USE_NATIVE_JSONFIELD=False):
from jsonfield_compat.forms import JSONFormField
from jsonfield.forms import JSONFormField as _JSONFormField
self.assertTrue(JSONFormField is _JSONFormField)
def from_field(cls, field):
if POSTGRES_AVAILABLE:
if isinstance(field, JSONField) or isinstance(field, HStoreField):
return cls(verbose_name=title(field.verbose_name))
def from_field(cls, field):
if POSTGRES_AVAILABLE:
if isinstance(field, JSONField) or isinstance(field, HStoreField):
return cls(verbose_name=title(field.verbose_name))
def get_prep_value(self, value):
if value is not None:
return _JsonAdapter(value, encoder=self.encoder)
return value
# Django 1.11 and above can use the contrib JSONField as it supports
# the encoder kwarg, which means we can use DjangoJSONEncode; 1.10
# and 1.9 must use our hacked together version (which is a direct
# copy+paste from the 1.11 codebase).
def __init__(self, fields=(), require_all_fields=False, **kwargs):
super(JSONField, self).__init__(**kwargs)
self.fields = fields
self.require_all_fields = require_all_fields
def formfield(self, **kwargs):
if self.fields:
defaults = {
'form_class': NestedFormField,
'fields': self.fields,
'require_all_fields': self.require_all_fields,
}
defaults.update(kwargs)
else:
defaults = kwargs
return super(JSONField, self).formfield(**defaults)
def test_should_query_postgres_fields():
from django.contrib.postgres.fields import IntegerRangeField, ArrayField, JSONField, HStoreField
class Event(models.Model):
ages = IntegerRangeField(help_text='The age ranges')
data = JSONField(help_text='Data')
store = HStoreField()
tags = ArrayField(models.CharField(max_length=50))
class EventType(DjangoObjectType):
class Meta:
model = Event
class Query(graphene.ObjectType):
event = graphene.Field(EventType)
def resolve_event(self, info):
return Event(
ages=(0, 10),
data={'angry_babies': True},
store={'h': 'store'},
tags=['child', 'angry', 'babies']
)
schema = graphene.Schema(query=Query)
query = '''
query myQuery {
event {
ages
tags
data
store
}
}
'''
expected = {
'event': {
'ages': [0, 10],
'tags': ['child', 'angry', 'babies'],
'data': '{"angry_babies": true}',
'store': '{"h": "store"}',
},
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected