次のモデルを検討してください。
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')