Reputation: 431
I've been trying to update a Django object with:
object_name.update(name="alfred")
The thing is that when I get the object name this way:
object_name = myobject.objects.get(id=object_id)
the method update won't work.
But when I get the object this way:
object_name = myobject.objects.filter(id=object_id)
it will work
Why does this happen? Is it because the last object is a queryset? Is there anyway to use .update with a django object?
thank you!
Upvotes: 0
Views: 103
Reputation: 2225
As the comments already stated, you can't use .update()
on a model instance itself - unless you created the function on the model yourself.
.update()
is being used on querysets
(see docs).
If you want to save the changes for a model instance, use save()
, example:
obj = MyModel.objects.get(...)
obj.some_field = 'some-other-value'
obj.save()
Also see the docs on how to save changes to objects.
Example on how you could implement MyModel.update()
:
class MyModel(...):
... # fields etc.
def update(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
self.save()
Upvotes: 2