25

I have a series of tests and cases in a database. Whenever a test is obsoleted, it gets end dated, and any sub-cases of that test should also be end dated. I see two ways to accomplish this:

1) Modify the save function to end date sub-cases.
2) Create a receiver which listens for Test models being saved, and then end dates their sub-cases.

Any reason to use one other than the other?

Edit: I see this blog post suggests to use the save method whenever you check given values of the model. Since I'm checking the end_date, maybe that suggests I should use a custom save?

Edit2: Also, for the record, the full hierarchy is Protocol -> Test -> Case -> Planned_Execution, and anytime one is end_dated, every child must also be endDated. I figure I'll end up doing basically the same thing for each.

Edit3: It turns out that in order to tell whether the current save() is the one that is endDating the Test, I need to have access to the old data and the new data, so I used a custom save. Here's what it looks like:

def save(self):
    """Use a custom save to end date any subCases"""
    try:
        orig = Test.objects.get(id=self.id)
        enddated = (not orig.end_date) and self.end_date is not None   
    except:
        enddated = False

    super(Test, self).save()

    if enddated:
        for case in self.case_set.exclude(end_date__isnull=False):
            case.end_date = self.end_date
            case.enddater = self.enddater
            case.save()
4

2 に答える 2

29

私は通常、次の経験則を使用します。

  • 保存が失敗しないようにデータを変更する必要がある場合は、上書きしますsave()(実際には別のオプションはありません)。たとえば、私が取り組んでいるアプリでは、選択肢のリストを持つテキスト フィールドを持つモデルがあります。これは古いコードと連動し、同様のテキスト フィールドを持っていた古いモデルを置き換えますが、選択肢のリストは異なります。古いコードは、私のモデルに古いモデルからの選択肢を渡すことがありますが、選択肢の間には 1:1 のマッピングがあるため、そのような場合、選択肢を新しいモデルに変更できます。でこれを行うのは理にかなっていますsave()
  • それ以外の場合、介入なしで保存を続行できる場合は、通常、保存後のシグナルを使用します。
于 2011-04-08T15:38:14.267 に答える
16

私の理解では、信号はモジュールを分離するための手段です。あなたのタスクは 1 つのモジュールでのみ発生するように見えるので、保存をカスタマイズします。

于 2011-04-08T15:39:33.333 に答える