python - 如何在 Django 中批量更新记录?
问题描述
我的数据库中有多个字段,我想更新提交按钮上的所有记录,请让我知道我该怎么做。
这是我的models.py
文件...
class Product(models.Model):
name=models.CharField(default=None)
type=models.CharField(default=None)
father=models.CharField(default=None)
model1=models.Foreignkey(Category, related_name='cat_product', on_delete=models.CASCADE)
这是我的views.py
文件...
def display_data(request, id):
test_display = Product.objects.all()
context = {
'test_display': test_display
}
return render(request, 'page.html', context)
这是我的page.html
文件...
<form method="POST" action={% url 'back:formupdate' %}
{% csrf_token %}
{% for test in test_display %}
<p>{{ test.name }}</p>
<p>{{ test.type }}</p>
<p>{{ test.phone }}</p>
<p><input type="text" name="father" value="{{test.father}}"></p>
<p>{{ test.model1 }}</p>
<button class='btn btn-success'>Update Record</button>
{% endfor %}
我想更新father
所有字段的记录,我想更新bulk records
……我想更新我所有数据库条目中的这条记录……
解决方案
通常,使用数据库中的模型实例并调用 save 方法将更新该实例,因此您也可以n
对操作数执行此操作。
for idVal in range(<fieldEntries>):
t = Product.objects.get(id=idVal)
t.father= <anyValue> # change field
t.save() # this will update only
但是,处理大量记录的效率很低。在这种情况下使用 - bulk_update
简而言之,您应该能够使用:
ModelClass.objects.filter(name='bar').update(name="foo")