我正在使用 DataTables.js 并尝试连接服务器端处理。我在服务器上使用 Django。
目前,Django 的数据如下所示:
{'draw': '1',
'columns[0][data]': '0',
'columns[0][name]': 'Brand',
'columns[0][searchable]': 'true',
'columns[0][orderable]': 'true',
'columns[0][search][value]': '',
'columns[0][search][regex]': 'false',
'columns[1][data]': '1',
'columns[1][name]': 'Sku',
'columns[1][searchable]': 'true',
'columns[1][orderable]': 'true',
'columns[1][search][value]': '',
'columns[1][search][regex]': 'false',
'columns[2][data]': '2',
'columns[2][name]': 'Name',
'columns[2][searchable]': 'true',
'columns[2][orderable]': 'true',
'columns[2][search][value]': '',
'columns[2][search][regex]': 'false',
'order[0][column]': '0',
'order[0][dir]': 'asc',
'order[0][name]': 'Brand',
'start': '0',
'length': '10',
'search[value]': '',
'search[regex]': 'false',
'_': '1725412765180'}
(作为字典)
但是,可能会出现不同数量的列和顺序值。所以我想将所有这些转换为几个关键变量:
但是我对python了解不多
嗯,这是一个纯粹的Python问题,与框架本身无关。无论如何,我能想到的唯一方法是收集元数据并使用它构建一个新对象。与此相关的一些事情:
data = { your_current_data }
"""
Access current data directly
and assign possible values to the new object.
"""
new_data = {
"start": data.pop("start"),
"length": data.pop("length"),
"search_value": data.pop("search[value]"),
"search_regex": data.pop("search[regex]"),
"draw": data.pop("draw"),
"columns": [],
"orders": [],
}
"""
Find metadata to build the new object.
1) columns: number of columns -> [0,1,2]
2) orders: number of orders -> [0]
3) keys_data: a matrix containing all keys ->
[
[k1, k2, k3...],
[...],
.
.
]
"""
columns = []
orders = []
keys_data = []
for key, value in data.items():
keys = key.split("[")
keys = [key.replace("]", "") for key in keys]
keys.append(value)
keys_data.append(keys)
if keys[0] == "columns":
if not keys[1] in columns:
columns.append(keys[1])
if keys[0] == "order":
if not keys[1] in orders:
orders.append(keys[1])
else:
pass
"""
Use columns and orders to loop through the matrix
and find it respective data to build a new object
to be appended to the new_data list.
"""
for number in columns:
obj = {"number": number}
for keys in keys_data:
if keys[0] == "columns" and keys[1] == number:
obj.update({f"{keys[-2]}": keys[-1]})
else:
pass
new_data["columns"].append(obj)
for number in orders:
obj = {"number": number}
for keys in keys_data:
if keys[0] == "order" and keys[1] == number:
obj.update({f"{keys[-2]}": keys[-1]})
else:
pass
new_data["orders"].append(obj)