Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: tracking if a field in the model is changed

I have a model:

class Object(Object1):
    name = models.CharField(max_length=255, blank=True)
    description = models.TextField(blank=True)
    date_updated = models.DateTimeField(blank=True, null=True)

I want to track if there is anything inserted into the date_updated field, then create another object in another model, without overriding the save method.

For example:

if date_updated:
    MyModel.objects.create(type="D", user=request.user)

Although I have tried this, but still no success.

like image 838
arrt_ Avatar asked Oct 21 '25 02:10

arrt_


1 Answers

You can use tracker field from django-model-utils.

Add a tracker to the model:

class Object(Model):
    name = models.CharField(max_length=255, blank=True)
    description = models.TextField(blank=True)
    date_updated = models.DateTimeField(blank=True, null=True)

    tracker = FieldTracker()

You can check in save() or in other places where you usually update the model:

if object.tracker.has_changed('date_updated'):

    create_new_object(data)
like image 175
Ibrohim Ermatov Avatar answered Oct 23 '25 14:10

Ibrohim Ermatov