I'm trying to use triggers to track total reactions on a Video model. Whenever the Reaction model gets an INSERT or UPDATE request of reaction, it should update the video's reaction count with the value returned from the COUNT function. I just can't seem to understand how to make a simple update statement/function of the Video. Need Help.
Current code:
class Video(models.Model):
...
reaction_count = models.IntegerField(default=0, null=False, blank=False, unique=False)
class VideoReaction(models.Model):
class Meta:
db_table = "video_reaction"
triggers = [
pgtrigger.Trigger(
name = "VideoReaction_TRIGGER_count",
when = pgtrigger.After,
operation = pgtrigger.Insert | pgtrigger.Update,
func = "id_video__reaction_count = COUNT(reaction)"
)
]
id = models.CharField(max_length=10, primary_key=True, null=False, blank=False, unique=True)
id_user = models.ForeignKey(User, db_column="id_user", on_delete=models.CASCADE)
id_video = models.ForeignKey(Video, db_column="id_video", on_delete=models.CASCADE)
reaction = models.BooleanField(null=False, blank=False)
...