0

这是我的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)预期工作。
我希望有人能帮我解决这个问题并解释这种奇怪之处(至少在我的菜鸟看来)

4

1 回答 1

3

此代码在删除后触发。也就是说,删除已经发生了,所以数据库中不再存在 Question 对象,查询它会失败。

您可能想改用预删除信号。

于 2012-07-12T23:33:21.310 回答