Django管理员在模型中对字段进行内联formset验证

时间:2016-04-04 16:16:23

标签: python django admin inline-formset

我正在学习python和django而且我遇到了困难。我有以下型号:

class State(models.Model):
    name = models.CharField(max_length=30)
    population = models.IntegerField()

class Candidate(models.Model):
    name = models.CharField(max_length=30)

# Represents the election result of a particular Candidate in a particular State
class Result(models.Model):
    candidate = models.ForeignKey(Candidate)
    state = models.ForeignKey(State)
    num_votes = models.IntegerField()

我的admin.py包含这个:

class CandidateAdmin(admin.ModelAdmin):
    fields = ['name']

class ResultInlineFormset(forms.models.BaseInlineFormSet):
    def clean(self):
        # Check that total number of votes doesn't exceed population
        sum = 0
        for form in self.forms:
            sum += form.cleaned_data.get('num_votes')
            # This is the part where I'm stuck
            if (sum > value_of_population_field_from_State_form):
                raise forms.ValidationError("Total number of votes cannot exceed state population")

class ResultInline(admin.TabularInline):
    model = Result
    extra = 0
    formset = ResultInlineFormset

class StateAdmin(admin.ModelAdmin):
    fields = ['name', 'population']
    inlines = [ResultInline]

admin.site.register(Candidate, CandidateAdmin)
admin.site.register(State, StateAdmin)

如您所见,我需要以某种方式检查总投票数(所有候选人的投票总数)是否不高于该州的人口。要做到这一点,我想我需要以状态形式访问人口字段的值,但我不知道如何做到这一点,或者它是否可能?

0 个答案:

没有答案