Reputation: 64783
Hello
How can I use the update()
method on a single model which I retrieved via Queryset.get()
? It seems like model. Model
doesn't have an update() method yet I cannot invoke .save() as I have a pre-save signals which messes things up.
EDIT: An idea would be passing some parameter to the save method and catching it at the pre_save signal, so that I can understand the purpose, how can this be done ?
Thanks
Upvotes: 1
Views: 6229
Reputation: 91
Calling the update()
method on the QuerySet doesn't invoke any signals nor does it use the Models' save()
method. See Django QuerySet documentation.
I would take a look at what Disqus does for atomic updates on Model instances.
See slide 30: http://www.scribd.com/doc/37072033/DjangoCon-2010-Scaling-Disqus
Upvotes: 0
Reputation: 4191
The update()
method is a bulk method. You cannot use it on a single instance.
You can do this
obj = ...get(...)
XX.objects.filter(id=obj.id).update(..)
But if presave is emitting an error, you are probably handling an inconsistent instance.
Upvotes: 1
Reputation: 5699
I would recommend updating the proper way using the save method. Maybe you can move you code from pre-save to post-save and check for the created flag. Or overload the save method and do what you have to do there. Another idea would be doing something like this:
User.objects.filter(pk=1)[0:1].update()
This slicing syntax returns a QuerySet upon which you can call your update method. You could call it without even without slicing, but then you yould theoretically update more than just your one model by mistake. Unless you filter by a primary key or something unique, that is.
Overloading the save method:
class MyModel(models.Model):
def save(self, some_value, *args, **kwargs):
# do your pre-save stuff here
super(MyModel, self).save(*args, **kwargs)
If need be you could even return from the save method or throw an excepption before calling the original save method. Then the model would not save. I don't think it is possible to do something like passing parameters from the save method to the signals. You can, however, pass additional parameters to the save method and then ommit them when calling the super method (I updated the example).
Upvotes: 2