3

I'm using Django 2.0.

I have a model like

class MyModel(models.Model):
    update_new = models.CharField(blank=True, max_length=200)
    modified = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

and updating model data using Model Manager

class MyModelManager(models.Manager):
    def get_queryset(self):
        return MyModelQueryset(self.model, self._db)

    def update_or_create(self, pk, **save_data):

        record = MyModel.objects.filter(
            pk=pk
        )

        if record.exists():

            # setting field manually for testing
            save_data['update_new'] = 'anuj'

            uc = record.update(**save_data)
            print(uc) # prints 1

            return record.first(), True

        record, created = self.get_queryset().get_or_create(
            pk=pk
            **save_data
        )

        return record, created

This works fine and value is updated. But modified field is not updated. Value in created and modified fields remain same (timestamp when record was created)

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

1 Answers1

7

This behaviour described in the docs:

The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100