2
votes

This seems like a pretty simple question but I'm having trouble finding the answer to it:

Do Django models with a foreign key ever call the save() method of the model they're pointing to when they are saved/changed?

I'm working on a model for SAT exams being taken, graded and scored--the last of which involves caching and cache invalidation--and trying to figure out just when I have to delete a cached Score object and recalculate it.

I have three models: ExamResponse, QuestionResponse, and ExamScore, which for concreteness we can say look like this:

class ExamResponse(models.Model):
    user = models.ForeignKey(User)
    exam = models.ForeignKey(Exam)

class QuestionResponse(models.Model):
    exam_response = models.ForeignKey(ExamResponse)
    answer = models.TextField()
    score = models.smallIntegerField(default=0)

class ExamScore(models.Model):
    exam_response = models.ForeignKey(ExamResponse)
    score = models.smallIntegerField(default=0)

Whenever a teacher grades an QuestionResponse (by changing the score field), I want to delete any ExamScore associated with the QuestionResponse's ExamResponse. Can I listen for a signal from a change to an ExamResponse object?

@receiver(post_save, model=ExamResponse)
def invalidate_exam_response_stats(sender, **kwargs):
    """
    Delete the ExamScore associated with this ExamResponse
    since it's become invalid.
    """

Or do I have to listen for the actual QuestionResponses to be saved?

@receiver(post_save, model=QuestionResponse)
def invalidate_exam_response_stats(sender, **kwargs):
    """
    Look up the QuestionResponse's ExamResponse, then delete
    the associated ExamScore.
    """
1
What's the problem? a circular execution?Gocht
What? No... the problem is uncertainty over whether ExamResponse's post_save signal will be sent when something with an fk to it is savedBrendan
@brendan if FK of a model is updated, signals are not triggered for that model.Ozgur Vatansever
@ozgur which is the same as if something with an FK to a model is updated, signals are not triggered for that model, right?Brendan
Also, @ozgur why not post an answer to answer the question?Brendan

1 Answers

1
votes

Answer: no, they do not do that.

I should listen to the QuestionResponse objects.

Thanks @ozgur for this answer.