Update Objects Django.How

Author avatar wrote on 02/06/2022

Update one record

    try:
        record = Account.objects.filter(id=1).first()
        record.balance = new_amount
        record.save()
        messages.success(request, "Company info has been updated." )
    except Exception as e:
        messages.error(request, "Something went wrong.")
        print("Exception Update balance ==========================")
        print(e)
        print("End of Exception  ==========================")


Short (.update) - used with .filter not .get

MyModel.objects.filter(pk=some_value).update(field1='some value')

Another short way (.select_for_update())

 Student.objects.select_for_update().filter(id=3).update(score = 10)

Update multiple

objects = MyModel.objects.filter(field1='Computer')
for obj in objects:
    obj.field2 = 'cool'
    obj.save()

Update or create

MyModel.objects.update_or_create(pk=some_value,defaults={'field1':'some value'})

Update based on the old field value

from django.db.models import Count, F, Value

MyModel.objects.filter(pk=some_value).update(field1=F('field1') + 1) # value of field1 = field1 + 1

bulk_update()

objs = [
    Entry.objects.create(headline='Entry 1'),
    Entry.objects.create(headline='Entry 2'),
 ]
objs[0].headline = 'This is entry 1'
objs[1].headline = 'This is entry 2'
Entry.objects.bulk_update(objs, ['headline'])

Update Modal Template

Button

Modal

  • https://stackoverflow.com/questions/2712682/how-to-select-a-record-and-update-it-with-a-single-queryset-in-django
  • https://stackoverflow.com/questions/15304378/django-error-model-object-has-no-attribute-update
  • CRUDgen Django CRUD generator