我正在尝试在表格中创建自定义ID。我想要的ID:
1909001 1909002
基本上,格式是yymm + counter,我想查询一下模型类中的最后一个id。尝试使用此link中的代码,但还是没有运气。
class Task(db.Model):
task_id = db.Column(db.Integer, primary_key=True)
subject = db.Column(db.String(100), nullable=False)
request_dt = db.Column(db.DateTime, nullable=False)
request_detail = db.Column(db.Text, nullable=False)
requestor = db.Column(db.String(100), nullable=False)
def get_last_id(self):
ym = date.today().strftime("%y%m")
qry = self.query.filter(self.task_id.like("{}".format(ym))).order_by(self.task_id.desc()).first()
if qry.task_id == '':
return ym + '001'
else:
lastid = qry.task_id
return "{:02d}".format(int(lastid[-3:]) + 1)
def __init__(self, subject, req_dt, req_detail, reqtor):
self.task_id = self.get_last_id()
self.subject = subject
self.request_detail = req_detail
self.request_dt = req_dt
self.requestor = reqtor
答案 0 :(得分:1)
我写了一个小烧瓶应用程序,可以帮助您解决问题。
您将获得与尝试获取的格式相同的自定义ID。
id custom_id subject request_detail request_dt request_or date
3 1909003 subject_3 request_detail_3 request_dt_3 request_or_3 2019-09-15 02:35:19.661868
2 1909002 subject_2 request_detail_2 request_dt_2 request_or_2 2019-09-15 02:35:06.191687
1 1909001 subject_1 request_detail_1 request_dt_1 request_or_1 2019-09-15 02:34:21.406240
app.py
from datetime import datetime, date
from flask import Flask, render_template, request, redirect, url_for
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm, CSRFProtect
from sqlalchemy import desc
from wtforms import StringField, SubmitField
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
SQLALCHEMY_DATABASE_URI = app.config['SQLALCHEMY_DATABASE_URI']
app.config['SECRET_KEY'] = app.config['SECRET_KEY']
csrf = CSRFProtect(app)
WTF_CSRF_SECRET_KEY = app.config['SECRET_KEY']
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
custom_id = db.Column(db.String(), nullable=False)
subject = db.Column(db.String(), nullable=False)
request_detail = db.Column(db.String(), nullable=False)
request_dt = db.Column(db.String(), nullable=False)
request_or = db.Column(db.String(), nullable=False)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def get_last_id():
qry = Task.query.order_by(Task.id.desc()).first()
x = qry.id
ym = date.today().strftime("%y%m")
q_custom_id = "" + ym + str(x).zfill(3) + ""
return q_custom_id
def __init__(self, custom_id, subject, request_detail, request_dt, request_or):
self.custom_id = custom_id
self.subject = subject
self.request_detail = request_detail
self.request_dt = request_dt
self.request_or = request_or
class TaskForm(FlaskForm):
subject = StringField(u'subject')
request_detail = StringField(u'request_detail')
request_dt = StringField(u'request_dt')
request_or = StringField(u'request_or')
submit = SubmitField('Save Post')
@app.route('/')
def id_order_task():
task_id = Task.query.order_by(Task.date.desc())
return render_template('index.html', task_id=task_id)
@app.route('/set-task', methods=['GET', 'POST'])
def set_task():
form = TaskForm()
try:
get_id = Task.query.order_by(desc('id')).first()
x: int = get_id.id + 1
y = date.today().strftime("%y%m")
if get_id:
custom_id = "" + y + str(x).zfill(3) + ""
except:
custom_id = str(date.today().strftime("%y%m") + str(1).zfill(3))
finally:
if request.method == 'POST':
add_task = Task(
custom_id=custom_id,
subject=request.form['subject'],
request_detail=request.form['request_detail'],
request_dt=request.form['request_dt'],
request_or=request.form['request_or']
)
db.session.add(add_task)
db.session.commit()
return redirect(url_for('id_order_task'))
return render_template('set-task.html', form=form)
if __name__ == '__main__':
app.run()
set-task.html
<div>
<form action="{{ url_for('set_task') }}" method="post">
{{ form.csrf_token }}
{{ form.subject.label }}
{{ form.subject }}
{{ form.request_detail.label }}
{{ form.request_detail }}
{{ form.request_dt.label }}
{{ form.request_dt }}
{{ form.request_or.label }}
{{ form.request_or }}
{{ form.submit }}
</form>
</div>
index.html
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 15px;
text-align: left;
}
</style>
<table>
<thead>
<tr>
<th>id</th>
<th>custom_id</th>
<th>subject</th>
<th>request_detail</th>
<th>request_dt</th>
<th>request_or</th>
<th>date</th>
</tr>
</thead>
<tbody>
{% for i in task_id %}
<tr>
<td>{{ i.id }}</td>
<td>{{ i.custom_id}}</td>
<td>{{ i.subject }}</td>
<td>{{ i.request_detail }}</td>
<td>{{ i.request_dt }}</td>
<td>{{ i.request_or }}</td>
<td>{{ i.date }}</td>
</tr>
{% endfor %}
</tbody>
</table>
答案 1 :(得分:1)
因此,基本上,您可以返回id表单任务,只需将字符串添加在一起并填充id。
def get_last_id():
qry = Task.query.order_by(Task.id.desc()).first()
x = qry.id
ym = date.today().strftime("%y%m")
q_custom_id = "" + ym + str(x).zfill(3) + ""
return q_custom_id
# print(Task.get_last_id())
我在数据库上有3个ID,这将打印最后一个ID,ID 3将变为:
1909003
我希望这对您有所帮助:P