Jason B
Jason B

Reputation: 365

django multiple update dates in one field

What would be the best way to create a "Update history" field in my Django Model so that I can keep track of multiple update dates?

I can create a model with last_updated = models.DateTimeField() and then have my view save the datetime to it, but what if I want to have a history of when the user has updated their post, and not just the most recent save?

Should it be a ManyToManyField or a CharField instead?

Upvotes: 2

Views: 2004

Answers (1)

Ludwik Trammer
Ludwik Trammer

Reputation: 25032

It's shouldn't be a field at all. Instead create a model, that will reference your main model using a ForeignKey:

class YourModel(models.Model):
    name = models.CharField(max_length=100)

class YourModelUpdateHistory(models.Model):
    your_model = models.ForeignKey('YourModel')
    updated = models.DateTimeField() 

This way you can have multiple dates for every model, while keeping the database properly normalized. It will also allow you in the future to add additional fields with other information about each update (for example who updated the object).

You should create a new YourModelUpdateHistory object whenever you update a YourModel object. You can even set it up so this is done automatically, thanks to the save() method (which is called by Django every time you save an object):

from django.utils import timezone

class YourModel(models.Model):
    name = models.CharField(max_length=100)

    def save(self, *args, **kwargs):
        super(YourModel, self).save(*args, **kwargs)
        YourModelUpdateHistory.objects.create(your_model=self, updated=timezone.now())

Upvotes: 3

Related Questions