我们从Python开源项目中,提取了以下29个代码示例,用于说明如何使用django.db.models.fields.NOT_PROVIDED。
def test_undefined(self): from django.db import models from django.db.models import fields class UndefinedClass(models.Model): pass alias = adapter.DjangoClassAlias(UndefinedClass, None) x = UndefinedClass() alias.applyAttributes(x, { 'id': pyamf.Undefined }) self.assertEqual(x.id, fields.NOT_PROVIDED) x.id = fields.NOT_PROVIDED attrs = alias.getEncodableAttributes(x) self.assertEqual(attrs, {'id': pyamf.Undefined})
def _encodeValue(self, field, value): if value is fields.NOT_PROVIDED: return pyamf.Undefined if value is None: return value # deal with dates .. if isinstance(field, fields.DateTimeField): return value elif isinstance(field, fields.DateField): return datetime.datetime( value.year, value.month, value.day, 0, # hour 0, # minute 0, # second ) elif isinstance(field, fields.TimeField): return datetime.datetime( 1970, # year 1, # month 1, # day value.hour, value.minute, value.second, value.microsecond ) elif isinstance(value, files.FieldFile): return value.name return value
def _decodeValue(self, field, value): if value is pyamf.Undefined: return fields.NOT_PROVIDED if isinstance(field, fields.AutoField) and value == 0: return None elif isinstance(field, fields.DateTimeField): # deal with dates return value elif isinstance(field, fields.DateField): if not value: return None return datetime.date(value.year, value.month, value.day) elif isinstance(field, fields.TimeField): if not value: return None return datetime.time( value.hour, value.minute, value.second, value.microsecond, ) return value
def test_NOT_PROVIDED(self): from django.db.models import fields self.assertEqual( pyamf.encode(fields.NOT_PROVIDED, encoding=pyamf.AMF0).getvalue(), '\x06' ) encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(fields.NOT_PROVIDED) self.assertEqual(encoder.stream.getvalue(), '\x00')
def conv_NullBooleanField(self, model, field, kwargs): from django.db.models.fields import NOT_PROVIDED def coerce_nullbool(value): d = {'None': None, None: None, 'True': True, 'False': False} if isinstance(value, NOT_PROVIDED): return None elif value in d: return d[value] else: return bool(int(value)) choices = ((None, 'Unknown'), (True, 'Yes'), (False, 'No')) return f.SelectField(choices=choices, coerce=coerce_nullbool, **kwargs)
def build_standard_field(self, field_name, model_field): field_class, field_kwargs = super(SampleSerializer, self).build_standard_field(field_name, model_field) if model_field.default is not NOT_PROVIDED: field_kwargs['default'] = model_field.default return field_class, field_kwargs
def __init__(self, *args, **kwargs): super(NullToDefaultMixin, self).__init__(*args, **kwargs) for field in self.Meta.fields: try: model_field = self.Meta.model._meta.get_field(field) if hasattr(model_field, 'default') and model_field.default != NOT_PROVIDED: self.fields[field].allow_null = True except FieldDoesNotExist: pass
def validate(self, data): for field in self.Meta.fields: try: model_field = self.Meta.model._meta.get_field(field) if hasattr(model_field, 'default') and model_field.default != NOT_PROVIDED and \ data.get(field, NOT_PROVIDED) is None: data.pop(field) except FieldDoesNotExist: pass return super(NullToDefaultMixin, self).validate(data)
def bulk_insert(object_list, show_sql = False): """ Generate the sql code for bulk insertion @param object_list: Django model objects """ if not len(object_list): return Model = type(object_list[0]) table_name = Model._meta.db_table fields_names = [ f.attname for f in Model._meta.fields if f.name != "id" ] sql = "insert into " + table_name + ' (' + ','.join(fields_names) + ') values \n' defaults = dict([(f.attname, f.default if f.default is not NOT_PROVIDED else "NULL") for f in Model._meta.fields]) auto_now_add = [f.attname for f in Model._meta.fields if getattr(f, "auto_now_add", False)] def get_values(ob, fields): ret = [] for field in fields: val = getattr(ob, field) if val is None: val = defaults[field] if field in auto_now_add: val = date.today().strftime("%Y-%m-%d") ret.append(str(val)) return ret lines = [] for ob in object_list: line = '("' + '","'.join(get_values(ob, fields_names)) + '")' line = line.replace('"NULL"', 'NULL') line = line.replace('"False"', 'False') line = line.replace('"True"', 'False') lines.append(line) sql += ',\n'.join(lines) + ";" # genesfile = open('sqlgenes', 'w') if show_sql: print(sql) return cursor = connection.cursor() # genesfile.writelines(sql) cursor.execute(sql) transaction.commit_unless_managed()
def getDecodableAttributes(self, obj, attrs, **kwargs): attrs = pyamf.ClassAlias.getDecodableAttributes( self, obj, attrs, **kwargs ) if self.decodable_properties: for n in self.decodable_properties: if n in self.relations: continue try: f = self.fields[n] except KeyError: continue attrs[f.attname] = self._decodeValue(f, attrs[n]) # primary key of django object must always be set first for # relationships with other model objects to work properly # and dict.iteritems() does not guarantee order # # django also forces the use only one attribute as primary key, so # our obj._meta.pk.attname check is sufficient) pk_attr = obj._meta.pk.attname pk = attrs.pop(pk_attr, None) if pk: if pk is fields.NOT_PROVIDED: attrs[pk_attr] = pk else: # load the object from the database try: loaded_instance = self.klass.objects.filter(pk=pk)[0] obj.__dict__ = loaded_instance.__dict__ except IndexError: pass if not getattr(obj, pk_attr): for name, relation in self.relations.iteritems(): if isinstance(relation, models.ManyToManyField): try: if len(attrs[name]) == 0: del attrs[name] except KeyError: pass return attrs