选择为整数的 Django 模型

Django Models with Choices as Integer

我正在尝试用 Django 制作一个反馈应用程序,但我无法做出评价。

在我的 models.py 中,我有 5 个选择,从非常差到非常好。但我希望它们可以用作数字,以便我可以评估整体价值。

阅读 Set Django IntegerField by choices=... name 后,我将我的评分从 VERYBAD = 'Very bad' 更改为 VERYBAD = 1 但不,我什至无法保存我的 value/form。

Feedback(models.Model):
    event = models.ForeignKey(Event)
    # Choice
    VERYBAD = 'Very bad'            #old
    BAD = 2                         #new
    OKAY = 3
    GOOD = 4
    EXCELLENT = 5
    RATING = (
        (VERYBAD, 'Very bad'),
        (BAD, 'Bad'),
        (OKAY, 'Okay'),
        (GOOD, 'Good'),
        (EXCELLENT, 'Excellent'),
    )

    # The ratings
    organisation = models.CharField(
        max_length=9,
        choices=RATING,
        default=OKAY,
    )
   ....

所以在我看来,我认为我可以做数学,但我做不到。

def rating(request, event_id):
    myevent = Event.objects.get(id=event_id)
    feedback_items = Feedback.objects.filter(event=myevent)
    num_of_items = len(feedback_items)

    def evaluate(feedback_items):
       # The overall rating
       organisation = 0
       for item in feedback_items: 
            organisation += item.organisation

       organisation /= num_of_items

    context = {'feedback_items':feedback_items,
           'num_of_items': num_of_items,
           'myevent': myevent,}

return render(request, 'feedback/rating.html', context)

`

显然,您必须将 organisation 设为 IntegerField,否则您将无法进行整数运算。如果您已经在生产中使用它,请使用一组迁移来添加一个新的 IntegerField,从现有的 CharField 值填充它(使用字典将旧字符串值映射到新的 int 值),最后删除原始字段。

此外,您可能想了解如何正确使用 Django 的 ORM 功能,例如获取相关模型实例和在数据库级别执行聚合,即:

from django.db.models import Sum, Count, Avg

def rating(request, event_id):
    myevent = Event.objects.get(id=event_id)

    # this is how you get related models...
    feedback_items = myevent.feedback_set.all()

    # and this is how you use SQL aggregation functions:
    values = feedback_items.aggregate(
        sum=Sum('organisation'),
        count=Count('pk'),
        avg=Avg('organisation')
        )

    # Now 'values' should be a dict with 'sum', 'count' and 'avg'
    # keys, and values['avg'] should be equal to 
    # float(values['sum']) / values['count']
    # FWIW you probably don't need the 'sum' field at all
    # I mentionned it so you can check whether 'avg' value
    # is correct...

     context = {
       'feedback_items':feedback_items,
       'num_of_items': values['count'],
       'avg': values['avg'],
       'myevent': myevent,
        }

     # etc