选择为整数的Django模型

时间:2016-12-06 15:17:39

标签: django integer django-views choicefield

我正在尝试在Django中制作反馈应用,但我无法进行评估。

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

阅读Set Django IntegerField by choices=... name后,我将评分从VERYBAD改为='非常糟糕'到VERYBAD = 1但是我甚至不能保存我的价值/形式。

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)

`

1 个答案:

答案 0 :(得分:0)

显然你必须使organisation成为IntegerField - 否则你不能指望进行整数运算。如果您已经在生产中使用它,请使用一组迁移来添加新的IntegerField,从现有的CharField值填充它(使用dict将旧字符串值映射到新的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