How can I create a search in Django?
I have a question model and a form, one of the fields of this model is userid = ForeignKey (User) . This works great on the question model, I can select the user from the fall.
But what's the tricky part, when I want to enumerate a question from the model, what is the best way to find the username from the Users table? because at this point I have no dropdown!
I want to have a simple thing like.
Question title asked: search username
source to share
Your field name ( userid
instead of user
) makes me think you might be confusing Django's behavior 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 Question
like Question
:
>>> question.user # the `User` instance
<User: username>
>>> question.user_id # the user primary key
1
It sounds like you can expect to question.userid
be the user's primary key rather than what it really is: the instance itself user
. When you access question.userid
, a database lookup is performed, but it is done automatically by Django using the value question.userid_id
. I would rename the field userid
to user
to avoid confusion.
From this perspective, I think you are trying to list the questions along with your associated users. If so, do something like this in your template:
<ol>
{% for question in questions %}
<li>{{ question }} asked by: {{ question.user }}</li>
{% endfor %}
</ol>
source to share
I find your question vague. If you want to get all the instances Question
that are associated with a specific instance User
, taking into account user_name
, you can do so:
questions = Question.objects.filter( userid__username='user_name' )
If you already have an instance User
(held in, say, a variable named User
) and would like to get all the objects associated with it Question
, you can get them with
questions = user.question_set.all()
source to share