Rizwan Mumtaz
Rizwan Mumtaz

Reputation: 3965

Django ORM update on QuerySet object

I have a queryset like.

message = Message.objects.select_related('user').get(id=1)
message_user = message.user

When i use .save() function on message_user it works.

message_user.first_name = 'ABC'
message_user.save()

When i use .update() function it does't.

message_user.update(first_name='ABC')

'User' object has no attribute 'update'

Upvotes: 0

Views: 543

Answers (1)

bakkal
bakkal

Reputation: 55448

update() is a method in the QuerySet class, but not in the Model class that your Message model inherits from.

Pre-Django 1.5 you can do Message.objects.filter(id=1).update(first_name='ABC') for a single row update, or Message.objects.filter(...).update(first_name='ABC') if you need bulk updates

You can also call it on the Manager of a model, e.g. Message.objects.update(first_name='ABC') to update all rows

Since Django 1.5 you can also specify which fields are to be saved in a single object update with:

message_user.first_name = 'ABC'
message_user.save(update_fields=["first_name"])

Upvotes: 2

Related Questions