views:

53

answers:

2

I have a template which is just a simple list of objects, and I would like to show the current user's rating for each object next to that object. Here are the relevant models:

class Problem(models.Model):
    question = models.TextField()
    answer = models.TextField()
    topic = models.ForeignKey(Topic)

class Attempt(models.Model):
    user = models.ForeignKey(User)
    problem = models.ForeignKey(Problem)
    confidence = models.CharField(max_length=10)
    date = models.DateTimeField(auto_now=True)

So the objects are 'problems' (displayed in the list just as their id) and the ratings are 'confidences'. And my template currently lists the problems for a given topic, and I would like to have the current user's confidence (if it exists) for each problem next to that problem.

Any ideas for how I can query for this and send it to / display it in the template? Thanks in advance for your help!

edit: I can alter the models if necessary. The attempts model is only for this, so it could be replaced entirely.

A: 

Found a solution using a slight modification of this answer to a similar question.

Chris
A: 

To make this work in a single query, I think you need to start your query from the Attempt model.

Attempt.objects.select_related().filter(problem__topic=mytopic, user=request.user)

That gives you a list of attempts for the current user on this particular problem. Then in your template you can iterate through this:

{% for attempt in attempts %}
{{ attempt.problem.topic }}
{{ attempt.confidence }}
Daniel Roseman
I think your query gives me a list of attempts for the current user on this particular topic, but there will also be problems in the topic for which there is no associated attempt, and I need to list those too.
Chris