使用数据库结果更新Django选择字段 [英] update django choice field with database results

查看:81
本文介绍了使用数据库结果更新Django选择字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django开发应用程序,当用户与其交互时,需要更新UI。例如,我有一个下拉字段,用户可以在其中选择一种饮料并提交,然后基于具有可用饮料的地点的下拉菜单,需要显示每个地点的价格和数量。然后,用户将进一步提交表单以进行第二次处理。

I am developing an application using django where the UI needs to be updated when user interacts with it. For instance I have a Drop down field where the user selects a drink and submits it then based on that a dropdown with the places that drink is available, price and quantity at each place needs to be displayed. The user will then further submit the form for second process.

据我了解,django中的表单是预先定义的,我无法想到使用该表单的方式我可以实现这一目标。

From my understanding the Forms in django are pre-defined and I am not able to think of a way using which I could achieve this.

我可以定义一个常规表单类

What I could come up was defining a regular form class

class dform(forms.Form):
    SOURCES_CHOICES = (
              (A, 'A'),
              (E, 'E'),
              )
  drink = forms.ChoiceField(choices = SOURCES_CHOICES)
  location = forms.ChoiceField(choices = **GET THIS FROM DATABASE**)
  quantity = forms.ChoiceField(choices = **GET THIS FROM DATABASE**)
  .
  .
  .

我的观点是,

def getdrink():
   if request.method == 'POST':
      #code for handling form
      drink =  dform.cleaned_data['drink']
      #code to get values from database

我不知道如何生成或填充或将我从数据库中获得的值附加到表单中的choicefield中。我确实尝试查找SO,但是这里没有任何解决方案正确解释了如何执行。另外,由于某些要求,我没有使用模型。因此我的数据库与模型完全无关。

I have no idea how to generate or populate or append the values i get from the database to the choicefield in my form. I did try looking up on SO but none of the solutions here explained properly how to do it. Also, due to certain requirements I am not using the models. So my database is not at all related to the models.

我全亏了,请帮帮我

推荐答案

如果您具有用于位置数量的模型,则 ModelChoiceField 应该起作用:

If you have models for location and quantity, a ModelChoiceField should work:

class dform(forms.Form):
    location = forms.ModelChoiceField(queryset = Location.objects.all())

否则,您将需要直接查询数据库,例如:

Otherwise, you'll need to query the database directly, for example:

class dform(forms.Form):
    location = forms.ChoiceField(choices = get_location_choices())

# elsewhere
from django.db import connection
def get_location_choices():
    cursor = connection.cursor()
    cursor.execute("select location_id, name from location_table")
    return cursor.fetchall()

SQL查询器在此处使用的y取决于您的数据库引擎和表架构。

The SQL query to use here depends on your database engine and table schema.

这篇关于使用数据库结果更新Django选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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