0
class EmployeeRating(models.Model):
    rating_1 = models.IntegerField(default = 0)
    rating_2 = models.IntegerField(default = 0)
    rating_3 = models.IntegerField(default = 0)
    rating_4 = models.IntegerField(default = 0)
    rating_4 = models.IntegerField(default = 0)
    total = models.IntegerField(default = 0)

使用模型表单获取值,自动将值分配给“总计”。

4

2 回答 2

1
class EmployeeRatingForm(forms.ModelForm):
    class Meta:
        model = EmployeeRating

    def __init__(self, *args, **kwargs):
        super(EmployeeRatingForm, self).__init__(*args, **kwargs)
        self.fields['total'].widget = forms.HiddenInput()

    def save(self, commit=True):
        rating = super(EmployeeRatingForm, self).save(commit=False)
        rating1 = self.cleaned_data['rating_1']
        rating2 = self.cleaned_data['rating_2']
        rating3 = self.cleaned_data['rating_3']
        rating4 = self.cleaned_data['rating_4']

        rating.total = rating1 + rating2 + rating3 + rating4
        rating.save()
于 2013-04-04T13:58:52.480 回答
1

1.不要重复自己

在模型中包含一个包含同一模型中其他一些字段的总数的字段似乎是个坏主意。更新一个而不是另一个太容易了,导致字段不一致。

所以我的建议是删除该total字段并在需要时计算它。

您可以向EmployeeRating模型中添加一个在 Python 中计算它的方法:

class EmployeeRating(models.Model):
    # ...

    @property
    def total_rating(self):
        return self.rating_1 + self.rating_2 + self.rating_3 + self.rating_4

如果您需要查询总数,您可以使用extra()

EmployeeRating.objects.extra(
    where = ['rating_1 + rating_2 + rating_3 + rating_4 > 10'])

2.标准化!

这很尴尬的原因是您的模型没有完全标准化。如果您有多个评分附加到一条EmployeeRating记录,实现它们的自然方法是有一个单独的表。如果这样做,您的模型将如下所示:

class EmployeeRating(models.Model):
    # ... other fields, e.g. foreign key to Employee model.

class Rating(models.Model):
    employee_rating = models.ForeignKey(EmployeeRating, related_name='ratings')
    rating = models.IntegerField()
    # ... other fields, e.g. who performed the evaluation, or when it was done.

然后您可以annotate()在需要获取总数时使用:

from django.db.models import Sum
EmployeeRating.objects.annotate(total_rating = Sum('ratings__rating'))
于 2013-04-04T15:20:51.507 回答