0

假设这些是 django 模型:

class Question():

    question = charfield()
    choice = charfield(choices = answer_choice)

class Answer():

    question = models.foreignkey(Question, related_name = 'answers')
    answerer = models.foreignkey('auth.User')
    answer = models.charfield()

我正在构建一个页面,其中显示 100 个问题,每个问题都User可以回答,但不能更改每个问题的答案。对于每个问题,我必须检查是否User已经存在Answerer。然后我制作模板标签:@register.filter def this_user_exists(user,obj): obj = obj.answers.filter(answerer_id = user.id) return obj

然后在模板上:

# obj is list of question
{% if not user|this_user_exists:obj %}
    # can answer
{% else %}
    # cannot answer
{% endif %}

问题是,对于每个问题,它会生成 1 个查询,因此对于 100 个问题,它将生成 100 个查询。我试过这个查询来生成问题Question.objects.all()Question.objects.prefetch_related('answers')但仍然有问题。有没有更好的方法来实现这一点而无需进行太多查询?

4

2 回答 2

2

为了减少查询,您可以先查询出您需要的答案,然后获取所有相关的答案,

answers = Answer.objects.select_related('answerer').filter(xxxx)

# fetch related user id's
userids_in_answer = [answer.answerer.id for answer in answers]

# fetch user ids
user_id_set = set(User.objects.filter(id__in=userids_in_answer).values('id', flat=True)

之后,您可以通过以下方式轻松知道用户是否存在,

for answer in answers:
  if answer.answerer.id in user_id_set:
      xxx

查询数量减少,您可以检查这是否有帮助。

于 2012-12-27T01:06:46.227 回答
0

在您看来:

answered_ids = [ans.question_id for ans in Answer.objects.filter(answerer=request.user)]

在您的模板中:

{% if not obj.id in answered_ids %}
    # can answer
{% else %}
    # cannot answer
{% endif %}
于 2012-12-27T01:06:52.743 回答