Py学习  »  Django

如何使用django将列表数据存储到数据库中?

Umer Khan • 4 年前 • 1239 次点击  

我有Django模型,有一个字段calle tag ou name和表单i AM从用户处获取输入,如下所示:

enter image description here

现在在views.py中,无论用户传递什么,我都从他那里得到了输入。 我把它分为以下几部分:

def function_name(request):
if request.method == 'POST':
    form = TagsForm(request.POST)
    if form.is_valid():
        # form = form.save(commit=False)
        tag_name = form.data['tag_name']
        split_tags = tag_name.split()
        # print(split_tags)
        form.save()
        return redirect('index_questions')
else:
    form = TagsForm()

context = {'form': form, }
return render(request, 'template.html', context)

有了这个,我将数据存储到表中,如下所示:

enter image description here

但我想将这两个名称作为单独的行添加到表中,如下所示:

我可以在views.py文件或模型中做什么来实现这一点? enter image description here

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39474
 
1239 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Iain Shelvington
Reply   •   1 楼
Iain Shelvington    4 年前

一个简单的解决方案是迭代标记并为每个标记创建一个对象

tags = tag_name.split()
for tag in tags:
    Tag.objects.create(tag_name=tag)

formsets 可以提供一个很好的解决方案来编辑/创建同一模型的多个