Sdude13
Sdude13

Reputation: 31

Django version of a database trigger?

I have two tables: Cameras & Timestamp, Timestamp has a foreign key to cameraID. Both camera and timestamp have a 'State' field. Each timestamp entry has a camera and a current state. I want to update the Camera.State value when Timestamp.State for that camera is updated. In SQL I know how to do this with a database trigger. But I am not sure how to achieve this in Django

Upvotes: 2

Views: 1665

Answers (1)

Marat
Marat

Reputation: 15738

There are two options: use Django signals or modify the Timestamp.save() to implement the desired behavior.

Example:

class Timestamp(models.Model):
    ...
    def save(self, *args, **kwargs):
        Camera.objects.filter(pk=self.camera_id).update(state=self.state)
        super(Timestamp, self).save(*args, **kwargs)

Upvotes: 2

Related Questions