2

We have a Model that includes an auto_add_now field and have decided that we need to be able to occasionally update it manually. However, in writing the DRF serializer / view it's unclear how best to handle this, since it's normally not editable we need to make a change. We're considering using the pre-save trick (AutoDateTimeField): Django auto_now and auto_now_add but that answer is 9 years old.

class AutoDateTimeField(models.DateTimeField):
    def pre_save(self, model_instance, add):
        return timezone.now()

#usage
created_at = models.DateField(default=timezone.now)
updated_at = models.AutoDateTimeField(default=timezone.now)

Are there any downsides? This is in an abstract base class which affects many models. Is there a better way (Django 1.11.7)?

Charles Thayer
  • 1,678
  • 1
  • 13
  • 17
  • 1
    AFAIK, **`auto_now_add`** field is ***not editable only in Django Admin*** – JPG Mar 12 '19 at 02:28
  • Use this ```models.DateTimeField(auto_now=True)``` now you can edit. – NVS Mar 12 '19 at 07:50
  • @JPG Thanks. Didn't work in the Serializer/View context either, in my DRF code. Digging a little into the source code: https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L1410 – Charles Thayer Mar 13 '19 at 05:44

0 Answers0