Python - 自动创建子记录

时间:2015-08-14 20:40:22

标签: python mysql django parent-child

我需要将MySQL表上的Trigger转换为Python / Django。

Trigger将select加载到游标中,循环并创建子记录。这是:

DECLARE cur CURSOR FOR select id from eval_category;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
  det_loop: LOOP
    FETCH cur INTO ids;
    IF done THEN
      LEAVE det_loop;
    END IF;
    INSERT INTO eval_evaluationdetail 
    (evaluation_id, category_id) VALUES (NEW.id,ids);
  END LOOP;
CLOSE cur;

要将其转换为Python,我修改了models.py,如下所示:

def save(self):
    super(Evaluation, self).save()
    for cat in Category.objects.all():
        self.EvaluationDetail.evaluation=self
        self.EvaluationDetail.category=cat
        self.EvaluationDetail.save()

这是最新的迭代,但它仍然无法工作:(非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

首先,save_model适用于ModelAdmin,而非Model。它不会做任何特别的事情。

您有两种选择:可以覆盖模型上的save,或使用post_save信号。以下是两种方法的其他答案的链接:

This answer有一个使用信号的好例子,

This question有一个覆盖save的好例子,包括讨论如何在两个选项之间做出选择。