gpt4 book ai didi

python - Django - 注释字典在模板中无法正确显示

转载 作者:行者123 更新时间:2023-11-30 22:15:53 25 4
gpt4 key购买 nike

我在 models.py 中得到了这些模型

class Rating(models.Model):
stars = models.IntegerField()
user_rating = models.ForeignKey(UserProfile, related_name="rater", on_delete=models.CASCADE)
user_rated = models.ForeignKey(UserProfile, related_name="rated", on_delete=models.CASCADE)
ride_number = models.ForeignKey(Ride, related_name="rider", on_delete=models.CASCADE)

class UserProfile(models.Model):
user = models.ForeignKey(User)

以及我的看法

def user_view(request):
avg = user_avg
total = user_count

context = {
'avg': avg,
'total': total
}

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

def user_avg():
avg = (Rating.objects
.values('user_rated').annotate(Avg('stars'))
.distinct())

return avg

最后我的模板看起来像这样

  {% for rating in avg %}
{{ avg }}
{% endfor %}

现在它的渲染是这样的;

[{'user_rated': 1L, 'stars__avg': 3.2222}, {'user_rated': 2L, 'stars__avg': 3.625}] [{'user_rated': 1L, 'stars__avg': 3.2222}, {'user_rated': 2L, 'stars__avg': 3.625}] 

我尝试将模板更改为 {{ avg.user_lated }} 但它没有给我带来任何结果,所以我不确定我在这里做错了什么。如何获取用户平均评分的名称而不是 user_lated

最佳答案

模板中的这一行:

{{ avg }}

应更改为:

{{ rating.user_rated }}: {{ rating.stars__avg }}

完整模板:

{% for rating in avg %}
{{ rating.user_rated }}: {{ rating.stars__avg }}
{% endfor %}

您的 2 个错误:1 - 循环变量是 rating - 您应该使用它来访问循环中的数据,2 - 要访问 dict 中的数据,您应该使用点表示法,请检查文档。

文档:https://docs.djangoproject.com/en/2.0/topics/templates/#variables

Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:

{{ my_dict.key }}
{{ my_object.attribute }}
{{ my_list.0 }}

要在注释结果中获取用户名,您应该将其添加到查询中的值中:

# assuming that your UserProfile model have name field
avg = (Rating.objects.values(
'user_rated', 'user_rated__name').annotate(Avg('stars')).distinct())

但要小心和注释 - 顺序很重要,结果值取决于值列表:

文档:https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#order-of-annotate-and-values-clauses

As with the filter() clause, the order in which annotate() and values() clauses are applied to a query is significant. If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause.

关于python - Django - 注释字典在模板中无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50155291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com