Dust8 的博客

读书百遍其义自见

0%

django 执行原生查询 文档里面的 Manager.raw(raw_query, params=None, translations=None) 里面有说 将查询字段映射为模型字段 就是根据 translations 参数来映射.

1
2
>>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
>>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)

通过 IDE 的跟踪可以看到它的实现方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class RawQuerySet:
...
@cached_property
def columns(self):
"""
A list of model field names in the order they'll appear in the
query results.
"""
columns = self.query.get_columns()
# Adjust any column names which don't match field names
for (query_name, model_name) in self.translations.items():
# Ignore translations for nonexistent column names
try:
index = columns.index(query_name)
except ValueError:
pass
else:
columns[index] = model_name
return columns
1
2
3
4
5
6
7
8
9
class RawQuery:
...

def get_columns(self):
if self.cursor is None:
self._execute_query()
converter = connections[self.using].introspection.identifier_converter
return [converter(column_meta[0])
for column_meta in self.cursor.description]

可以看到关键点是 self.cursor.description

直接执行自定义 SQL 里面有把查询结果变成字典类型的方法

1
2
3
4
5
6
7
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]

python 官方的 sqlite3 模块里面的 description字段描述可以看到

description
这个只读属性将提供上一次查询的列名称。 为了与 Python DB API 保持兼容,它会为每个列返回一个 7 元组,每个元组的最后六个条目均为 None。
对于没有任何匹配行的 SELECT 语句同样会设置该属性。

虽然知道它的实现, 还是感觉在 django 里面多此一举, 因为正常 queryset 没法用, 用原生的直接用数据库的 AS 关键字就可以了.

安装软件

PowerShell Core

oh-my-posh

修改配置

notepad.exe \$Profile

1
2
3
4
5
6
7
8
9
Import-Module posh-git
Import-Module oh-my-posh
Set-Theme Paradox

Set-PSReadlineKeyHandler -Key Tab -Function Complete # 设置 Tab 键补全
Set-PSReadLineKeyHandler -Key "Ctrl+d" -Function MenuComplete # 设置 Ctrl+d 为菜单补全和 Intellisense
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo # 设置 Ctrl+z 为撤销
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward # 设置向上键为后向搜索历史记录
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward # 设置向下键为前向搜索历史纪录

参考链接

js 从服务端获取 policy 后直传阿里云 oss.
实际并不需要用 demo 里面的插件, 原生 js 更容易理解.
服务端和客户端的 demo 都让人更糊涂, 估计是外包弄的, 水平不是一般的次.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>

<body>
<div>
<input id="file" type="file" />
<button id="upload" type="button">upload</button>
</div>
<script type="text/javascript">
let button = document.getElementById("upload");
button.addEventListener("click", (event) => {
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");
formData.append("success_action_status", 200);
formData.append("OSSAccessKeyId", "");
formData.append("policy", "");
formData.append("signature", "");
formData.append("key", "vid/course-video-application/a.zip");
formData.append("file", fileField.files[0]);

fetch("http://xx.oss-cn-shenzhen.aliyuncs.com", {
method: "post",
body: formData,
});
});
</script>
</body>
</html>

参考链接

django admin 后台需要导出 excel 文件. 除了用插件, 也可以自己简单的实现.
lib 目录是一些自己写的库, 在 settings 文件里面把它加入了 sys.path.
导出的时候需要选中要导出的数据才能导出, 不然只点导出按钮是无效的. 因为模型里面有些字段是 choice
所以增加判断, 有 get_xx_display 属性的时候, 返回比较友好的显示.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# lib/export.py
from django.http import HttpResponse
from openpyxl import Workbook


class ExportExcelMixin:
'''
通用导出 Excel 文件动作
'''

def export_as_excel(self, request, queryset):
'''
导出为 excel 文件. 文件名为 app名.模型类名.xlsx.

:param request:
:param queryset:
:return:
'''
# 用于定义文件名, 格式为: app名.模型类名
meta = self.model._meta
# 模型所有字段名
field_names = [field.name for field in meta.fields]
field_verbose_names = [field.verbose_name for field in meta.fields]

# 定义响应内容类型
response = HttpResponse(content_type='application/msexcel')
# 定义响应数据格式
response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'

wb = Workbook()
ws = wb.active
ws.append(field_verbose_names)

# 遍历选择的对象列表
for obj in queryset:
# 将模型属性值的文本格式组成列表
data = []
for field in field_names:

if hasattr(obj, f'get_{field}_display'):
# 可选属性取显示的值
value = getattr(obj, f'get_{field}_display')()
else:
value = getattr(obj, field)

data.append(f'{value}')

ws.append(data)

# 将数据存入响应内容
wb.save(response)

return response

# 该动作在 admin 中的显示文字
export_as_excel.short_description = '导出Excel'
1
2
3
4
5
6
7
8
9
10
11
# admin.py
from django.contrib import admin


from export import ExportExcelMixin
from .models import *

class XXAdmin(admin.ModelAdmin, ExportExcelMixin):
...

actions = ['export_as_excel']

参考链接

使用原生 sql 插入数据库的时候, 如果字段太多会导致写起来太麻烦,就想了个自动生成插入语句的代码.
前提是字段名要和数据库一致, 如果不一致可以自己在加一层代码, 做一些键名映射.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

def insert(conn,table_name, data, sep='?'):
cur = conn.cursor()

# 把字典变成键值对数组
zipped = []
for key, value in data.items():
zipped.append((key, value))

# 把键值对数组变成对应的键数组和值数组
keys, values = zip(*zipped)

sql = f"insert into {table_name}({', '.join(keys)}) values ({', '.join([sep for _ in range(len(values))])})"
cur.execute(sql, values)
conn.commit()
cur.close()