Django:获取QuerySet中对象的偏移量

时间:2018-06-03 01:49:03

标签: django database model django-queryset

我有两个模型,一个是问题文本,第二个是用户和问题特定的答案。我的用户回答了很多问题,如果有问题,我该如何找到相应答案的索引?索引表示先前答案的数量/给定答案的位置。

更具体地说,当我查询以下内容时:

from django.db import models
from django.conf import settings

class Question(models.Model):
    body = models.TextField()

class Answer(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)
    question = models.ForeignKey(Question, models.CASCADE)
    answer = models.TextField()


def getIndexOfAnswer(user, question):
    answer = user.answer_set.filter(user=user, question=question).all().order_by("pk")
    return answer.???index()???

如何获取给定用户的答案索引(例如,按PrimaryKey排序)?

1 个答案:

答案 0 :(得分:0)

我拥有它!

def getIndexOfAnswer(user, question):
    answer = user.answer_set.filter(question=question).get()
    return user.answer_set.filter(pk__lte=answer.pk).count() - 1