简体   繁体   English

如何在 Django 中批量更新记录?

[英]How to Bulk update records in Django?

I have multiple fields in my database and I want to update all records on submit button, Please let me know how i can do it.我的数据库中有多个字段,我想更新提交按钮上的所有记录,请告诉我该怎么做。

Here is my models.py file...这是我的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)

here is my views.py file...这是我的views.py文件...

def display_data(request, id):
    test_display = Product.objects.all()
    context = {
        'test_display': test_display
    }
    return render(request, 'page.html', context)

here is my page.html file...这是我的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 %}

I want to update father record in all fields, I want to update bulk records ... I want to update this record in all my database entries....我想更新所有字段中的father记录,我想更新bulk records ……我想更新我所有数据库条目中的这条记录……

Typically, using the model instance from the database and calling the save method will update that instance, you can therefore do this for n number of operations too.通常,使用数据库中的模型实例并调用 save 方法将更新该实例,因此您也可以对n次操作执行此操作。

for idVal in range(<fieldEntries>):
    t = Product.objects.get(id=idVal)
    t.father= <anyValue> # change field
    t.save() # this will update only

However, it's inefficient for handling large volumes of records.但是,处理大量记录时效率低下。 In this case use - bulk_update在这种情况下使用 - bulk_update

In short, you should be able to use:简而言之,您应该能够使用:

ModelClass.objects.filter(name='bar').update(name="foo")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM