django中的非规范化场

时间:2010-09-13 19:58:27

标签: django django-models

我发现很难在django模型中对场进行非规范化。我有:

class AnswerSet(models.Model):
    title = models.CharField(max_length=255)
    num_answers = models.PositiveIntegerField(editable=False, default=0)
    answers = models.ManyToManyField(Answer, through='AnswerSetAnswer')
    ...

class AnswerSetAnswer(models.Model):
    answer = models.ForeignKey(Answer)
    answer_set = models.ForeignKey(AnswerSet)
    ...

我希望num_answers包含集合中答案数的计数。

如果5个答案最初与AnswerSet“Food”相关联,并且我编辑了一个以便它与AnswerSet“Colors”相关联,那么如何使用“Food”重新计算AnswerSet中的答案数量?所有信号似乎只发送新数据,所以我不能只重写保存方法。

我尝试过使用m2m_changed信号,但是当我通过管理表单编辑关系时,它永远不会被调用。

无论如何,这是我的代码:

def update_answer_set_num_answers(sender, **kwargs):
    """
    Updates the num_answers field to reflect the number of answers
    associated with this AnswerSet
    """
    instance = kwargs.get('instance', False)

    print "no instance"              # never gets here

    if not instance:
        return

    action = kwargs.get('action')

    print "action: ", action

    if (action != 'pre_remove' and action != 'pre_add' and action != 'clear'):
        return

    reverse = kwargs.get('reverse')

    if reverse:
        answer_set = instance.answer_set
    else:
        answer_set = instance.answer_set
    num_answers = AnswerSetAnswer.objects.filter(answer_set=answer_set.id).count()

    if (action == 'pre_remove'):
        num_answers -= int(kwargs.get('pk_set'))
    elif (action == 'pre_add'):
        num_answers += int(kwargs.get('pk_set'))
    elif (action == 'clear'):
        num_answers = 0

    answer_set.num_answers = num_answers

    print 'n a: ', answer_set.num_answers
    answer_set.save()


m2m_changed.connect(update_answer_set_num_answers, \
  AnswerSet.answers.through, weak=False)

1 个答案:

答案 0 :(得分:1)

你真的需要对此进行反规范吗?您可以使用简单的聚合来计算它:

from django.db.models import Count
answersets = AnswerSet.objects.all().annotate(num_answers=Count('answers')