gpt4 book ai didi

python - 如何在模板中引用函数的结果? Django

转载 作者:行者123 更新时间:2023-11-28 21:47:55 24 4
gpt4 key购买 nike

我有这些模型:

# this is model for user
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')

profilepic = models.ImageField(blank=True)


city = models.ForeignKey(City)
slug = models.SlugField(unique=True)


def save(self, *args, **kwargs):
self.slug = slugify(self.user.username)
super(UserProfile, self).save(*args, **kwargs)

def __unicode__(self):
return self.user.username

@property
def avg_rating(User):
return UserProfile.userrating_set.all().aggregate(Avg('rating'))['rating__avg']


# this is the model for user ratings - one to many relationship with User
class UserRating(models.Model):
user = models.ForeignKey(User)
comment = models.CharField(max_length=500)
for_username = models.CharField(max_length=128)
rating = models.IntegerField(default=5)

def __unicode__(self):
return unicode(self.rating)

我想在我的模板中引用属性 (avg_rating) 的结果,这样我就可以显示每个用户的评分。我试过了它显示空白结果:

{% for user in users %}
{{ user.profile.avg_rating }}

此外,这是被调用的 View :

def index(request):
user_list = User.objects.select_related().order_by('-userrating')[:5]

city_list = City.objects.order_by('-name')[:5]

context_dict = {"users": user_list, "cities" : city_list}

return render(request, "index.html", context_dict)

我目前正在学习 Django,如果这很明显,我深表歉意。

最佳答案

avg_ratingUser 参数根本没有使用。尝试将其重写为:

def avg_rating(self):
return self.user.userrating_set.all().aggregate(Avg('rating'))['rating__avg']

您还可以删除 @property 装饰器,因为您还可以使用相同语法(即不使用 ())在 Django 模板中使用方法,例如:

{{ user.profile.avg_rating }}

关于python - 如何在模板中引用函数的结果? Django ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35936693/

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