4

次のモデルを検討してください。

class Arena(models.Model):
  crowd_capacity = models.PositiveInteger()
  # more fields here

class Section(models.Model):
  name = models.CharField(max_length=10)
  crowd_capacity = models.PositiveInteger()
  arena = models.ForeignKey(Arena, related_name='sections')

admin.py:

class SectionInline(admin.StackedInline):
    model = Section
    fk_name = 'arena'
    extra = 1

class ArenaAdmin(admin.ModelAdmin):
    inlines = [
        SectionInline,
    ]

すべてのsection.crowd_capacityの合計が合計arena.crowd_capacityを超えていないことを確認するための検証メソッドを追加したいと思います。

最初は、cleanメソッドを使用してカスタムSectionFormSetを作成したかったのですが、arena.crowd_capacityを取得する方法がわかりませんでした。

また、Arenaにクリーンなメソッドを追加しようとしました。これは、きれいな赤い検証エラーを示していますが、問題を修正することはできません。すべてのセクションが保存された後にArenacleanメソッドが実行され、section.crowd_capacityとセクションを変更しても問題が発生しなかったようです。

私が試した検証方法:

def clean(self):
        super(Arena, self).clean()
        capacity = 0
        for s in self.sections.all():
            capacity += s.crowd_capacity

        if capacity > self.crowd_capacity:
            raise ValidationError('The sum of all sections crowd capacity '
                                  'exceeds arena crowd capacity')
4

1 に答える 1

4

わかりました、私はついに方法を見つけました。

明確にするために、すべてのセクションの群集容量の合計がアリーナの群集容量の合計を超えていないことを検証したいと思います。

最終的な解決策は(admin.pyで):

class SectionFormSet(forms.models.BaseInlineFormSet):
    def clean(self):
        if any(self.errors):
            return
        capacity = 0
        for f in self.forms:
            try:
                capacity += f.cleaned_data['crowd_capacity']
                if capacity > f.cleaned_data['arena'].crowd_capacity:
                    raise ValidationError('The sum of all sections crowd capacity '
                                              'exceeds arena crowd capacity')
            except KeyError:
                # in case of empty form
                pass


class SectionInline(admin.StackedInline):
    model = Section
    formset = SectionFormSet

class ArenaAdmin(admin.ModelAdmin):
    inlines = [
        SectionInline,
    ]

それだけです。モデルに変更はありません。魅力のように機能します:)

于 2012-11-27T08:43:13.067 に答える