5

How can we change the default process of the update method for a queryset in django as it does not call save method for each object. And since I have overridden the save method, I need it to be called each time the object is changed. I looked for django doc but this is just for get_query_set, Is there is something similar for the update method also.

Art
  • 2,836
  • 4
  • 17
  • 34
ashish
  • 2,090
  • 3
  • 17
  • 16

1 Answers1

11

This worked for me


class MyQuerySet(models.query.QuerySet):
    def update(self, *args, **kwargs):
        # here queryset update method overridden
        pass

class NewManager(models.Manager):
    def get_queryset(self):
        # this is to use your custom queryset methods
        return MyQuerySet(self.model, using=self._db)

class MyModel(models.Model):
    objects = NewManager()
    myfield = models.SomeTypeOfField(**kwargs)
mcabrams
  • 686
  • 1
  • 6
  • 23
ashish
  • 2,090
  • 3
  • 17
  • 16
  • Do you really need the override for update() at the NewManager level? – Chad Aug 07 '13 at 03:00
  • 1
    @chad: yes, MyModel.objects.update(**kwargs) actually uses method defined in NewManager and MyModel.objects.filter(**kwargs).update(**kwargs) uses the one defined in MyQuerySet – ashish Aug 07 '13 at 20:44
  • 1
    Actually maybe it depends on the Django version being used? The source code for the update() function for manager classes is just `return self.get_query_set().update(*args, **kwargs)`. So if you want both `filter().update()` and `objects.update()` to behave the same, looks like you just need to override it at the queryset level (unless I'm misunderstanding something). – Chad Aug 08 '13 at 04:09
  • @Chad: you are correct. Update method is only defined for querysets only and yes manage update method call the update method at queryset level – ashish Aug 27 '13 at 17:37