How can i create a lookup in Django?

By : Gath

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

By : Gath


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

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:

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

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()
By : ayaz

I agree with the the two thread approach. I would also have two static buffers and a shared enum. The sending thread should have this logic.

    wait for timer
    grab mutex
    check enum {0, 1}
    send buffer 0 or 1 based on enum
    release mutex
end loop

The other thread would have this logic:

    check enum
    choose buffer 1 or 0 based on enum (opposite of other thread)
    generate data
    grab mutex
    flip enum
    release mutex
end loop

This way the sender always has a valid buffer for the entire time it is sending data. Only the generator thread can change the buffer pointer and it can only do that if a send is not in progress. Additionally, the enum flip should never take so many cycles as to delay the higher priority sender thread for very long.

This video can help you solving your question :)
By: admin