0

I want to add creation and update timestamps to several models in my django app. And I wonder what way is the best practice?

I found that it can be done with auto_now and auto_now_add (or preferably via custom save() method). I call this programmatic way.

Another way that comes to mind is defining a trigger function and assigning it to multiple database tables on the level of database (postgresql).

So what is the best practice of doing things like that? (This may include total price calculations and any other column info that is calculated using other column data). Triggers or code?

Note:

This might be an opinion-based question. If so, Let me know in the comment, I will delete the question after I hear one or two opinions of an experienced developer.

  • Are you interested in recording when someone updates the DB by other means than your app? If yes, you will need a trigger. – JGH Mar 30 '21 at 14:16

1 Answers1

0

Using django signals maybe is a solution.
It likes a trigger in database;
https://docs.djangoproject.com/en/3.1/topics/signals/

I use it like this:

from django.dispatch.dispatcher import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    is_validated = models.BooleanField(default=False)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
yanqzhi
  • 382
  • 3
  • 8