Django - 从当前用户的视图准备对象 [英] Django - Prepare objects from a view for Current User

查看:149
本文介绍了Django - 从当前用户的视图准备对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个模型

class Exercise(models.Model):
  name = models.CharField(max_length=50)
  def __unicode__(self):
    return self.name

class Score(models.Model):
  """Scores of users by exercise"""
  exo = models.ForeignKey(Exercise)
  user = models.ForeignKey(User)
  score = models.IntegerField()
  class Meta:
    unique_together = (('exo', 'user',),)

我有一个模板,显示练习 s。

I have a template which displays the Exercises.

<ul>
  {% for exo in exos %}
    <li>{{ exo }}</li>
  {% endfor %}
</ul>

这是视图

def view_exos(request):
  """Lists Exercises"""
  objs = {
    'exos': Exercise.objects.all(),
  }
  return render_to_response('content/contents.html', objs
  , context_instance=RequestContext(request)
  )

现在,我想在每个前显示当前用户的分数练习(如果有的话)以这种方式从模板中访问它:

Now I'd like to display the Score of the current user in front of each Exercise (if there is one) in order to access it from the template in this manner:

<li>{{ exo }} - {{ exo.user_score }}</li>


推荐答案

我会做的是让所有用户目前的成绩在前,创建一个字典映射练习得分,然后将该分数作为每个练习的属性添加。如下:

What I'd do would be to get all the user's current scores up front, create a dictionary mapping exercise to score, then add the score as an attribute of each exercise. Something like:

user_scores = request.user.score_set.all()
score_dict = dict((sc.exo_id, sc.score) for sc in user_scores)
exos = Exercise.objects.all()
for ex in exos:
    ex.current_user_score = score_dict.get(ex.id)

现在 exos 中的每个练习都有一个 current_user_score 属性,这是该练习的当前用户得分(或无)。

Now each exercise in exos has a current_user_score attribute, which is the current user's score for that exercise (or None).

这篇关于Django - 从当前用户的视图准备对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆