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>