SQL填充的Python表单下拉选项 [英] Python form drop down options populated by sql

查看:45
本文介绍了SQL填充的Python表单下拉选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇文章.我是编程新手.我正在尝试在Python中构建一个包含下拉列表的html表单.我目前已对下拉选项进行了硬编码,但希望从sql中填充选项,以便如果针对选项更新了数据库,则该选项将动态更改.我还必须提到,此下拉列表被用作对数据表的搜索/过滤器,该数据表也是从数据库中填充的.

This is my first post. I am fairly new to programming. I am attempting to build a html form in Python which contains a drop down. The drop down options, I currently have hard coded, but want to populate the options from sql, so that it will be dynamically changing if the database is updated for the options. I also must mention that this drop down is being used as a search/filter for a data table which is also populated from the database.

请提供任何建议.

硬编码下拉列表:

<div class="dropdown col-lg-2">
  <label for="form_status" id="form_status">STATUS</label>
    <select class="form-control input-sm" id="form_status" name="form_status">
      <option {% if var_status == ""%}selected="selected"{% endif %} value=""></option>
      <option {% if var_status == "1001"%}selected="selected"{% endif %} value="1001">Active</option>
      <option {% if var_status == "1018"%}selected="selected"{% endif %} value="1018">Obsolete</option>
    </select>
</div>

搜索过滤器后面的代码

if request.method == 'GET':
    var_status = ''

if request.method == 'POST':

    if 'form_status' in request.POST and request.POST['form_status']:
        var_status = request.POST['form_status']

SQL查询:

SELECT  DISTINCT "CODE" AS status_code, "LONGDESC" AS status FROM v_status WHERE "CODE" =1001 OR "CODE" = 1018 ORDER BY "CODE"


1001 | Active
1018 | Obsolete

推荐答案

此处需要多少细节.您有SQL查询,但没有存储它的对象.您是否完全熟悉从python运行SQL查询?如果是这样,那么简单的for循环和字符串格式将根据数据库结果构建选项.

How much detail do you need here. You have the SQL query but no object storing it. Are you familiar at all with running SQL queries from python? If so then a simple for loop and string formatting will build the options from the database result.

for line in sqlResponse:
    print("<option value='%s'>%s</option>" % (
        str(line.status_code), str(line.status)
    )

如果没有,那么除了首先了解python教程中的基本SQL并确定适用于数据库的框架/库之外,没有其他简单的答案.我个人将SQLAlchemy ORM与Python结合使用.

If not, then without knowing what your database is and what library you intend to use there's no easy answer other than look around at basic SQL in python tutorials first and decide on a framework/library that works with your database. I personally use SQLAlchemy ORM with Python.

这篇关于SQL填充的Python表单下拉选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆