tags:

views:

359

answers:

2

I have a Question model & Form, one of the fields in this model is userid=ForeignKey(User), this Works perfectly well on the Question Model, am able to pick the user from a drop down.

But kind a tricky when i want to list the question from the model, which is the best way to lookup the user name from the Users table? becouse at this point i cant have the dropdown!

I want to have a simple thing e.g.

Question Title asked by:lookup user Name

A: 

I find your question vague. If you want to fetch all Question instances that are related to a particular User instance given a user_name, you can do thus:

questions = Question.objects.filter( userid__username='user_name' )

If you already have a User instance (held, say, in a variable called user) and would like to fetch all Question objects related to it, you can get those with:

questions = user.question_set.all()
ayaz
+3  A: 

The name of your field (userid instead of user) makes me think that you may be confused about the behavior of Django's ForeignKey.

If you define a model like this:

from django.contrib.auth.models import User
from django.db import models

class Question(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=100)
    ...

    def __unicode__(self):
        return self.title

And then instantiate a Question as question:

>>> question.user # the `User` instance
<User: username>

>>> question.user_id # the user's primary key
1

It looks like you may be expecting question.userid to be the user's primary key, rather than what it actually is: the User instance itself. When you access question.userid, a database lookup is performed, but it's done automatically by Django using the value of question.userid_id. I would rename the userid field to user to avoid confusion.

With that out of the way, I think what you are trying to do is list the questions along with their associated users. If that's the case, do something like this in your template:

<ol>
{% for question in questions %}
    <li>{{ question }} asked by: {{ question.user }}</li>
{% endfor %}
</ol>
jpwatts