django - 运行Avg()时显示人类可读

时间:2017-08-27 21:14:22

标签: python django

我正逐步搞清楚这一点。我希望用户能够根据4个条件(difficulty_rating,workload_rating,book_rating,attendance_rating)对博客帖子进行评分。我在models.py中使用了一些选项来为用户提供选择。

之后,感谢StackOverflow的用户,我能够计算出每个值的平均值,并将它们显示在每个帖子的顶部。

问题是它们显示为具有长小数的浮点数。有没有办法显示人类的可读性?哪个来自我的模型元组?

我在模板中编写了一个{%if%}语句,硬编码所有内容,但我很确定必须有更好的方法。

models.py

class Post(models.Model):
    STATUS_CHOISES = (

        ('draft', 'Draft'),
        ('published', 'Published'),

        )
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique=True)
    content = models.TextField()
    seo_title = models.CharField(max_length=250)
    seo_description = models.CharField(max_length=160)
    author = models.ForeignKey(User, related_name='blog_posts', default=settings.AUTH_USER_MODEL)
    published = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=9, choices=STATUS_CHOISES, default='draft')

    def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.slug])


    def avg_ratings(self):
        return self.comments.aggregate(
            Avg('difficulty_rating', output_field=FloatField()),
            Avg('workload_rating', output_field=FloatField()),
            Avg('book_rating', output_field=FloatField()),
            Avg('attendance_rating', output_field=FloatField()),
        )


    def __str__(self):
        return self.title



class Comment(models.Model):
    difficulty_rating_choices = (

        (1, 'Very Easy'),
        (2, 'Easy'),
        (3, 'Moderate'),
        (4, 'Hard'),
        (5, 'Very Hard'),

    )

    workload_rating_choices = (

        (1, 'Very Light'),
        (2, 'Light'),
        (3, 'Moderate'),
        (4, 'Heavy'),
        (5, 'Very Heavy'),

    )

    book_rating_choices = (

        (1, '$'),
        (2, '$$'),
        (3, '$$$'),
        (4, '$$$$'),
        (5, '$$$$$'),

    )

    attendance_rating_choices = (

        (1, 'Not Required'),
        (2, 'Required'),


    )
    post = models.ForeignKey(Post, related_name="comments")
    user = models.CharField(max_length=250)
    email = models.EmailField()
    title = models.CharField(max_length=250)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    approved = models.BooleanField(default=False)
    difficulty_rating = models.IntegerField(choices=difficulty_rating_choices)
    workload_rating = models.IntegerField(choices=workload_rating_choices)
    book_rating = models.IntegerField(choices=book_rating_choices)
    attendance_rating = models.IntegerField(choices=attendance_rating_choices)


    def approved(self):
        self.approved = True
        self.save()

    def __str__(self):
        return self.title

views.py

def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
template = 'blog/post/post_detail.html'
context = {

    'post': post,

}
return render(request, template, context)

模板

{% with avg_ratings=post.avg_ratings %}
<h1>Difficulty: {{ avg_ratings.difficulty_rating__avg }}</h1>
        <h1>Workload: {{ avg_ratings.workload_rating__avg }}<h1>
        <h1>Book Cost: {{ avg_ratings.book_rating__avg }}<h1>
        <h1>Attendance: {{ avg_ratings.attendance_rating__avg }}<h1>

    {% endwith %}

3 个答案:

答案 0 :(得分:1)

使用django模板过滤器https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#floatformat

例如:

{{ avg_ratings.difficulty_rating__avg|floatformat:"-3" }}

如果您希望将“人类可读”替换为值范围,请创建自己的自定义模板过滤器。

请参阅https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/#howto-writing-custom-template-filters

您可以执行类似的操作(添加关卡的范围):

from django import template

register = template.Library()

@register.filter
def rating_humanize(value): # Only one argument.
    if value < 1.0:
        return 'Very Easy'
    elif value < 2.0:
        return 'Easy'
    else:
        return 'Hard'

更好的实现方法是创建范围到字符串映射的列表,然后找到匹配的范围并为其返回字符串。

答案 1 :(得分:0)

使用DecimalField(decimal_places=2)代替FloatField可能有所帮助。

Decimal docs

答案 2 :(得分:0)

不确定这是否是最佳解决方案,但我想出的是,您需要在avg_ratings模型中更新Post方法:

import math

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

    def avg_ratings(self):
        ratings = {}
        data = self.comments.aggregate(
            Avg('difficulty_rating', output_field=FloatField()),
            Avg('workload_rating', output_field=FloatField()),
            Avg('book_rating', output_field=FloatField()),
            Avg('attendance_rating', output_field=FloatField()),
        )

        for key, val in data.items():
            key = key.replace('__avg', '')
            scaled_val = int(math.ceil(val))
            display = ''
            choices = getattr(CommentTest, '{}_choices'.format(key))
            for choice_display, choice_val in choices:
                if scaled_val == choice_val:
                    display = choice_display
                    break
            if not display:
                raise Exception('Display for "{}" avg with value "{}" not found.'.format(key, scaled_val))
            ratings[key] = (scaled_val, display, val)
        return ratings

然后在模板中:

{% with avg_ratings=post.avg_ratings %}
  <h1>Difficulty: {{ avg_ratings.difficulty_rating.0 }} - {{ avg_ratings.difficulty_rating.1 }}</h1>
  <h1>Workload: {{ avg_ratings.workload_rating.0 }} - {{ avg_ratings.workload_rating.1 }}<h1>
  <h1>Book Cost: {{ avg_ratings.book_rating.0 }} - {{ avg_ratings.book_rating.1 }}<h1>
  <h1>Attendance: {{ avg_ratings.attendance_rating.0 }} - {{ avg_ratings.attendance_rating.1 }}<h1>
{% endwith %}

avg_ratings方法的作用是以这种格式准备评级词典:

{'difficulty_rating': (2, 'Easy', 1.9), ..}

每个键的值将是一个包含三个值的元组:

  • 第一个值将是avg的缩放值,例如如果平均值为1.7,则视为2。
  • 第二个值是人类可读的显示值。
  • 第三个值是缩放的实际平均值。

我在这个逻辑中使用了math.ceil,但是你可以稍后决定你自己的逻辑。