def to_dict(self, dehydrate_fields=None, excludes=None, json_fields=None, exclude_common=True): """ Deserialize model object to simple dict object """ dehydrate_fields = dehydrate_fields or [] excludes = excludes or [] if exclude_common: excludes.extend(MODEL_COMMON_FIELDS) json_fields = json_fields or [] data = {} for field in self._meta.fields: field_name = field.name if field_name in excludes: continue field_value = getattr(self, field_name) if not field_value: data[field_name] = None continue if field_name in json_fields: data[field_name] = json.loads(field_value) continue if isinstance(field, (ImageField, ImageFieldFile, FileField)): data[field_name] = get_absolute_url_path(field_value.url) continue if isinstance(field, ForeignKey): data[field_name] = field_value.to_dict() if field_name in dehydrate_fields else str(getattr(self, '{}_id'.format(field_name))) continue if isinstance(field, (DateField, DateTimeField)): data[field_name] = datetime2timestamp(field_value) continue if isinstance(field, (UUIDField,)): data[field_name] = str(field_value) continue if isinstance(field, URLField): data[field_name] = get_absolute_url_path(field_value) continue data[field_name] = field_value return data
def dehydrate(self, bundle): """ Do some customize behaviors for project requires 1. convert all DateTimeField's value to a timestamp value 2. Convert all Media FileField's value to be its absolute url path """ for k, v in bundle.data.iteritems(): # convert all datetime/date to timestamp value if isinstance(v, (datetime, date)): bundle.data[k] = datetime2timestamp(v) continue # return the absolute url path of the media file if hasattr(bundle.obj, k) and isinstance(getattr(bundle.obj, k), (FileField, ImageField)): bundle.data[k] = get_absolute_url_path(v) continue return bundle
def dehydrate(self, bundle, exclude_common=True): """ Do some customize behaviors for project requires 1. convert all DateTimeField's value to a timestamp value 2. Convert all Media FileField's value to be its absolute url path 3. if exclude_common = True, the api return value will not includes the common fields """ bundle = super(BaseModelResource, self).dehydrate(bundle) for field in bundle.obj._meta.fields: # convert all datetime/date to timestamp value # used to exclude common model fields if exclude_common: if field.name in BaseModelResource.Meta.excludes: if field.name in bundle.data: del bundle.data[field.name] continue # used to exclude resource specific exclude fields if field.name in self._meta.excludes: if field.name in bundle.data: del bundle.data[field.name] continue field_value = getattr(bundle.obj, field.name) if not field_value: continue if isinstance(field, (DateField, DateTimeField)): bundle.data[field.name] = datetime2timestamp(field_value) continue if isinstance(field, (FileField, ImageField)): bundle.data[field.name] = get_absolute_url_path( field_value.url) continue return bundle