从信号中检索的模型实例无法按预期工作

时间:2012-07-12 22:26:34

标签: python django django-signals

以下是来自models.py

的代码
#Models.py
....
class Question(models.Model):
    text = models.TextField(unique=True)
    exam = models.ForeignKey(Exam)
    level = models.ForeignKey(Level)
    paper = models.ForeignKey(Paper)
    topic = models.ForeignKey(Topic)
    date_added = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    text = models.CharField(max_length=125)
    is_correct = models.BooleanField()
    explanation = models.TextField(blank=True)
    date_added = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

@receiver(post_delete, sender=Question)
def update_redis_deleted(sender, **kwargs):
    host = getattr(settings, 'SESSION_REDIS_HOST', 'localhost')
    port = getattr(settings, 'SESSION_REDIS_PORT', 6379)
    db = getattr(settings, 'SESSION_REDIS_DB', 0)

    server = redis.StrictRedis(host, port, db)

    pipe = server.pipeline()

    question = kwargs['instance']
    answer_set_list = question.answer_set.all()
    answer = Answer.objects.get(question=question)

从我的测试中,当我删除一个Question实例时,answer_set_list是一个空列表,而answer会抛出DoesNotExist错误。在我的tests.py中,question.answer_set.all()Answer.objects.get(question=question)按预期工作 我希望有人可以帮助我解决这个问题,并解释这种奇怪的现象(至少对我的小说来说)

1 个答案:

答案 0 :(得分:3)

此代码在删除后触发。换句话说,删除已经发生,因此数据库中不再存在Question对象,查询它将失败。

您可能想要使用预删除信号。