在使用for循环时将数据提供给数据库的问题 [英] Issues with feeding data into database when using for loop

查看:566
本文介绍了在使用for循环时将数据提供给数据库的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模板中,我为某些字段使用了循环。

In my template I have used for loop for some fields

<div class="register_div">

    <p>Title:</p>
    <p>{{ form.title }}</p>
</div>
<div class="register_div">

    <p>Upload Images :</p>
    <p>{{ form.image }}</p>
</div>

{% for item in product %}

<div class="register_div">

    <p>{{ item.Name }} <input type="text" name="custom[{{item.id}}]"/></p>

</div>

{% endfor %}


<div class="register_div">

    <p>Price:</p>
    <p>{{ form.price }}</p>
</div>

正如代码所示,有一个字段使用for循环,如果该字段有三个记录,它显示三个文本框,以便用户可以将数据提供给所有三个字段,但是我的数据库中的表只有一个字符串用于他的id,一个用于他的vaue。

As code shows there is one field which using for loops if that field has three records then in the form it shows three text boxes so that user can feed data to all three fields, but my table in database have only one col for his id and one for his vaue.

so我如何将数据提供给我的数据库,以便如果用户感觉到所有三个文本框,那么它可以轻松地存储在我的数据库中。
如果可以通过三个重复条目的标题,图像和价格,然后它的确定,但它应该有三个不同的项目名称和相应的值。

so how i can feed data to my database so that if user feels all three text boxes then it can be easily stored in to my database. If it is possible by three duplicate entry for title , image and price then its ok,But it should have take three different item name and there corresponding value.

例如

如果有三个项目名称从for循环出来,那么用户看到的是。

if there are three item names comes out from for loop then what user see is.

title
image
item 1 ---> its vaue
item 2 ---> its vaue
item 3 ---> its vaue
price

现在我们应该在数据库中存储,如

now it should we store in database like

id  title  image   item_name    item_value   price
1    asd    a.jpg   item1           value 1      1111
2    asd    a.jpg   item2           value 2     555
3    asd    a.jpg   item3           value 3      789

或者还有其他有效的方法这样做请让我知道

or there is any another efficient way to do this please let me know

推荐答案

这样做的高效方法是确保您的模型与此数据匹配,然后使用模型表单

The "efficient way" to do this is to make sure your models match this data, and then use Model FormSets.

如果由于某些神秘原因,您不想定义模型以匹配您的数据,您可以使用正常的 formets

If, for some arcane reason, you don't want to define models to match your data, you can use normal formsets instead.

如果你不是家庭我喜欢 Django表单,我强烈建议您尝试了解这些。 您的真实答案对django表单有一个相当全面的演练。

If you aren't familiar with Django forms, I highly recommend you try to understand those first. This answer by yours truly has a fairly comprehensive walkthrough on django forms.

这篇关于在使用for循环时将数据提供给数据库的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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