开发者

django: Selecting questions that was not asked

I am creating small django application which holds some few questions (and answers for them)

What I want to do is to show user random question, but only from those which was not solved by him yet. I wonder how to do this.

For now, I defined user profile model this way:

class UserProfile(models.Model):
    rank = models.IntegerField(default = 1)
    solvedQ = models.ManyToManyField(Question)
    user = models.ForeignKey(User, unique=True)

So solved problems are added this way:

if user.is_authenticated():
    profile = user.get_profile()
    profile.rank += 1
    profile.solvedQ.add(Question.objects.get(id=id))

开发者_Go百科Now if the view must show random question, but not from already solved list...

Is there a good way to intersect Questions and solvedQuestions.... so question is chosen from the unsolved list?


ManyToMany relationships are automatically symmetrical in Django ... http://docs.djangoproject.com/en/1.1/topics/db/models/#many-to-many-relationships

Run a query from the Question model

Without seeing your Quesion model, I assume it will end up looking something like this:

possible_questions = Questions.objects.filter(~(UserProfile=profile))

I believe that query will give you the all results where the User related to the Question does not match the current user. I am not very familiar with running "not" queries. A quick lookup told me that the '~' will do it but you should double-check.

Then, you can just grab a random one from the returned queryset.

** edit **

Looks like you can grab the random right in the query by doing something like:

possible_questions = Questions.objects.filter(~(UserProfile=profile)).order_by('?')

Then just use the first one returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜