Turn an SQLAlchemy model into a dict of field names and values.

    Based on https://stackoverflow.com/a/37350445/1579058
331296
def object_as_dict(obj):
    
    return {c.key: getattr(obj, c.key)
            for c in inspect(obj).mapper.column_attrs}
1204746
def _value_list_to_sciobj_dict(
    sciobj_value_list, lookup_list, lookup_dict, generate_dict
):
    """"""

    sciobj_dict = {}

    # for sciobj_value, lookup_str in zip(sciobj_value_list, lookup_list):
    lookup_to_value_dict = {k: v for k, v in zip(lookup_list, sciobj_value_list)}

    for field_name, r_dict in lookup_dict.items():
        if r_dict["lookup_str"] in lookup_to_value_dict.keys():
            sciobj_dict[field_name] = lookup_to_value_dict[r_dict["lookup_str"]]

    for field_name, annotate_dict in generate_dict.items():
        for final_name, generate_func in annotate_dict["generate_dict"].items():
            sciobj_dict[field_name] = generate_func(lookup_to_value_dict)

    return sciobj_dict
1078374
def to_dict(self):
        
        return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type}
1221817
def field_to_dict(field, instance):
    
    # avoid a circular import
    from django.db.models.fields.related import ManyToManyField

    return (many_to_many_field_to_dict(field, instance) if isinstance(field, ManyToManyField)
            else field.value_from_object(instance))
1254891
def get_fields(model, fields, meta=None):
    
    model = get_model(model)
    if fields is not None:
        f = fields
    elif meta and hasattr(model, meta):
        m = getattr(model, meta)
        if hasattr(m, 'fields'):
            f = m.fields
        else:
            f = model._fields_list
    else:
        f = model._fields_list
        
    fields_list = []
    for x in f:
        field = {}
        if isinstance(x, str):  #so x is field_name
            field['name'] = x
        elif isinstance(x, tuple):
            field['name'] = x[0]
            field['field'] = x[1]
        elif isinstance(x, dict):
            field = x.copy()
        else:
            raise UliwebError('Field definition {!r} is not right, it should be just like (field_name, form_field_obj)'.format(x))
        
        if 'prop' not in field:
            if hasattr(model, field['name']):
                field['prop'] = getattr(model, field['name'])
            else:
                field['prop'] = None
        
        fields_list.append((field['name'], field))
    return fields_list
1320201
def get_fields_dict(self):
        
        fields = []
        for field_name in self.model_admin.get_inspect_view_fields():
            fields.append(self.get_dict_for_field(field_name))
        return fields
937919
def get_params_from_sqlalchemy_url(db_url):
        # type: (str) -> Dict[str,Any]
        
        result = urlsplit(db_url)
        return {'database': result.path[1:], 'host': result.hostname, 'port': result.port,
                'username': result.username, 'password': result.password, 'driver': result.scheme}
1146898
def to_dict(self):
        

        # 1. extract the schema fields
        data = self.extract_fields()

        # 2. include custom key-value pairs listed in the mapping dictionary
        for key, attr in self.attributes.iteritems():
            if key in self.ignore:
                continue  # skip ignores
            # fetch the mapped attribute
            value = getattr(self.context, attr, None)
            if value is None:
                value = getattr(self, attr, None)
            # handle function calls
            if callable(value):
                value = value()
            # map the value to the given key from the mapping
            data[key] = api.to_json_value(self.context, key, value)
        return data
593404
def as_dict(self):
        
        d = {"@module": self.__class__.__module__,
             "@class": self.__class__.__name__,
             "name": self.name, "options": self.options}
        if len(self.subkeys) > 0:
            subkeys = []
            for subkey in self.subkeys:
                subkeys.append(subkey.as_dict())
            d.update({"subkeys": subkeys})
        return d
470884
def get_columns(model=None, fields=None, meta=None):
    
    if model:
        M = get_model(model)
    else:
        M = None
    if fields is not None:
        f = fields

    if M:
        if meta and hasattr(M, meta):
            m = getattr(model, meta)
            if hasattr(m, 'fields'):
                f = m.fields
            else:
                f = M._fields_list
        else:
            f = M._fields_list

    columns = []
    for x in f:
        if isinstance(x, str):  # so x is field_name
            field_name = x
        elif isinstance(x, dict):
            field_name = x['name']
        else:
            raise UliwebError("Field definition is not right, it should be just like str or {'name':xxx}")

        if '.' in field_name:
            model_name, field_name = field_name.split('.')
            M = get_model(model_name)

        if not M:
            raise UliwebError("Model can't be empty, because field name not has `model.` prefix")

        if field_name in M.c:
            columns.append(M.c[field_name])

    return columns
856327
def fetchall_as_dictlist(self, sql: str, *args) -> List[Dict[str, Any]]:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        self.db_exec_with_cursor(cursor, sql, *args)
        try:
            rows = cursor.fetchall()
            fieldnames = [i[0] for i in cursor.description]
            dictlist = []
            for r in rows:
                dictlist.append(dict(zip(fieldnames, r)))
            return dictlist
        except:  # nopep8
            log.exception("fetchall_as_dictlist: SQL was: " + sql)
            raise
957553
def _parse_fields(self, result, field_name):
        
        field_list = []
        for key, value in result.get('schema', {}).get(field_name, {}).items():
            if key not in field_list:
                field_list.append(key)
        return field_list
4674
def field_dict(self, model):
        
        if self.field_names is None:
            return dict([(f.name, f) for f in model._meta.fields
                         if isinstance(f, models.DateField)])
        else:
            return dict([(f.name, f)
                         for f in model._meta.fields
                         if isinstance(f, models.DateField) and
                            (f.name in self.field_names)])
1262021
def to_dict(self, columns=None):
        
        if columns:
            assert len(columns) == len(self.feature_names)
        d = [
            dict([
                (columns[i] if columns else col_name, row[i])
                for i, col_name in enumerate(self.feature_names)
            ])
            for row in self.data
        ]
        return d
1148302
def _build_query_dict(self, formdata=None):
        
        if self.is_valid() and formdata is None:
            formdata = self.cleaned_data
        key = "{field}__{operator}".format(**formdata)
        if formdata['operator'] == "isnull":
            return {key: None}
        elif formdata['operator'] == "istrue":
            return {formdata['field']: True}
        elif formdata['operator'] == "isfalse":
            return {formdata['field']: False}
        return {key: formdata['value']}
272902
def dump(schema):
    
    result = {}

    for name, _ in iteritems(schema.getschemas()):

        if hasattr(schema, name):
            val = getattr(schema, name)

            if isinstance(val, DynamicValue):
                val = val()

            if isinstance(val, Schema):
                val = dump(val)

            result[name] = val

    return result
616710
def from_dict(cls, data, model):
        
        model_provided = model is not None
        result = {}
        for name, new_value in data.items():
            kwargs = {
                'name': name,
                'new_value': new_value,
            }
            if model_provided:
                kwargs['params'] = model.get_field_params(name)
            result[name] = cls(**kwargs)
        return result