This article mainly introduces how to update and delete multiple objects in Django. Django is the most popular among Python frameworks. For more information, see
Update multiple objects
For example, we want to change the name of Apress Publisher from "Apress" to "Apress Publishing ". If you use the save () method, for example:
>>> p = Publisher.objects.get(name='Apress')>>> p.name = 'Apress Publishing'>>> p.save()
This is equivalent to the following SQL statement:
SELECT id, name, address, city, state_province, country, websiteFROM books_publisherWHERE name = 'Apress';UPDATE books_publisher SET name = 'Apress Publishing', address = '2855 Telegraph Ave.', city = 'Berkeley', state_province = 'CA', country = 'U.S.A.', website = 'http://www.apress.com'WHERE id = 52;
(Assume that the ID of Apress is 52)
In this example, we can see that the save () method of Django has updated not only the value of the name column, but also all columns. If columns other than name may be changed by other processes, it is more wise to change only the name column. To change a specified column, we can call the update () method of the result set object: example:
>>> Publisher.objects.filter(id=52).update(name='Apress Publishing')
The equivalent SQL statement is more efficient and does not cause race conditions.
UPDATE books_publisherSET name = 'Apress Publishing'WHERE id = 52;
The update () method is valid for any result set (QuerySet), which means you can update multiple records at the same time. The following example shows how to change the country field value of all Publisher from U. S. A' to 'USA ':
>>> Publisher.objects.all().update(country='USA')2
The update () method returns an integer value, indicating the number of affected records. In the preceding example, the value is 2.
Delete object
To delete an object in a database, you only need to call the delete () method of the object:
>>> p = Publisher.objects.get(name="O'Reilly")>>> p.delete()>>> Publisher.objects.all()[
]
Similarly, we can call the delete () method in the result set to delete multiple records at the same time. This is similar to the update () method mentioned in the previous section:
>>> Publisher.objects.filter(country='USA').delete()>>> Publisher.objects.all().delete()>>> Publisher.objects.all()[]
Exercise caution when deleting data! To prevent accidental deletion of all data in a table, Django requires that all () be displayed when deleting all data in the table (). For example, the following operations may fail:
>>> Publisher.objects.delete()Traceback (most recent call last): File "
", line 1, in
AttributeError: 'Manager' object has no attribute 'delete'
Once the all () method is used, all data will be deleted:
>>> Publisher.objects.all().delete()
If you only need to delete part of the data, you do not need to call the all () method. Let's take a look at the previous example:
>>> Publisher.objects.filter(country='USA').delete()