导读:由于除了id字段以外其它所有字段都不具有唯一性,为了使得数据库容易理解,我们需要把数个字段组合起来,形成容易理解的可视化主键字段,以下是过程
过程
数据表:
1. 活动小组表 (act_gp):
• gp_name(小组名称)
• act_name(活动名称)
• date(期数)
我们从 act_gp 表中查询数据,并生成主键。
模型代码
# 活动小组表
db.define_table(
'act_gp',
Field('gp_name', 'string', required=True, unique=True, label='小组名称'),
Field('act_name', 'string', required=True, unique=True, label='活动名称'),
Field('date', required=True, label='期数'),
format='%(gp_name)s'
)
编写控制器从 act_gp 表中查询数据,并生成 unique_key:
控制器代码
def group_keys():
"""
从数据库查询活动小组信息,并生成期数-小组名称-活动名称的主键
"""
# 从 act_gp 表查询数据
rows = db(db.act_gp).select(db.act_gp.gp_name, db.act_gp.act_name, db.act_gp.date)
# 将查询结果转化为列表并生成 unique_key
data = []
for row in rows:
unique_key = f"{row.gp_name}-{row.act_name}-{row.date}"
data.append({
"gp_name": row.gp_name,
"act_name": row.act_name,
"date": row.date,
"unique_key": unique_key
})
return dict(data=data)
视图代码
{{extend 'layout.html'}}
<div class="container-wrapper">
<h1>小组主键生成</h1>
<p>以下是从数据库中获取的活动小组信息,以及生成的主键:</p>
<!-- 表格显示数据 -->
<table border="1" style="width: 100%; text-align: center; border-collapse: collapse;">
<thead>
<tr>
<th>期数</th>
<th>小组名称</th>
<th>活动名称</th>
<th>主键 (Unique Key)</th>
</tr>
</thead>
<tbody>
{{if len(data) == 0:}}
<tr>
<td colspan="4">暂无数据</td>
</tr>
{{else:}}
{{for row in data:}}
<tr>
<td>{{=row["date"]}}</td>
<td>{{=row["gp_name"]}}</td>
<td>{{=row["act_name"]}}</td>
<td>{{=row["unique_key"]}}</td>
</tr>
{{pass}}
{{pass}}
</tbody>
</table>