使用Django表单/模型更新多个数据库行

时间:2014-08-14 04:50:59

标签: python django

需要使用django来管理一些特定于应用程序的数据库设置。由于底层的数据库结构,我遇到了困难(我相信!)。不幸的是 - 这是预先存在的,无法改变。

基本上,我想允许用户在下拉框中选择一个选项。此选项将映射到数据库表中的一行或多行,因此:

用户会看到一个与ID' ID相关的下拉框。 (在此示例中为2)包含

香精:  - 巧克力   - 草莓(初选)   - 奶酪

但是在后端,更改的结果如下:

table: FOOD_CONFIG
ID (non-unique) | parameter  | value  |
1               | Colour     | Brown  |
1               | Feel       | Sticky |
2               | Colour     | Red    |
2               | Feel       | Sticky |

当用户设置Cheese时,它将更改为ID,以便表格变为:

ID (non-unique) | parameter  | value  |
1               | Colour     | Brown  |
1               | Feel       | Sticky |
2               | Colour     | Yellow |
2               | Feel       | Solid |

作为额外的复杂层,基于Food是否具有某些参数,我想在表单上动态生成字段。 (所以如果食物ID有一个“刺激性”参数,也许会出现一个气味选择器。)

我无法理解正确的工作工具。

问题(我认为)是模型看起来像:

class FoodConfigTable(models.Model):
    ID = models.ForeignKey(FoodType)
    parameter = models.CharField(max_length=254)
    value = models.CharField(max_length=254)
    class Meta:
        db_table = u'food_config_table'

并从中创建ModelForm将允许最终用户直接修改参数或值 - 而不是我需要的。

然而,我正努力找出正确的工作流程。也许这样的事情?:

def flavour_selector_view(request, food_id):

    fct = FoodConfigTable()
    fct.objects.filter(ID=food_id)

    if request.method == 'POST":
        # Make the model update the db

    # Create the dynamic form - can't fill out during construction as fields are created dynamically later (???)
    fcf = FoodConfigurationForm()
    fields = fct.get_fields_for_id(food_id)             #{'Flavour', 'Odour', ... , etc}        

    for f in fields:
        choices = fct.get_choices_for_field(food_id, f)  #[(1, 'chocolate'), (2, 'strawberry'), ... , etc]
        if f in request.POST:
            value = request.POST[f]
        else:
            value = fct.get_current_field_value(f)   
        fcf[f] = forms.ChoiceField(choices = choices, initial = value)

    render_to_response('flavour_selector.html', {'food_configuration_form': fcf})

在完全输入之后,我觉得我在正确的轨道上,但是在Django中没有坚实的基础让我很有意思,我错过了一种明显的方法,或者缺乏或危险的做法。 。

值得一提的是python版本是2.5,而django 1.0.2

(编辑:关于ChoiceField创建的小错误修复)

1 个答案:

答案 0 :(得分:0)

我不知道这是否适用于django 1.0。查看django的get_or_create模型方法,并尝试使用它来简化代码。我个人会这样做:

# After user has made selection etc.
color, _ = FoodConfigTable.get_or_create(
           id=userid, parameter='Colour', value=flavor.color)
feel, _ = FoodConfigTable.get_or_create(
           id=userid, parameter='Feel', value=flavor.feel)

因为每个用户似乎只有一个选择

相关问题