【问题标题】:Django: Getting the offset of an object in a QuerySetDjango:获取 QuerySet 中对象的偏移量
【发布时间】:2018-11-12 17:29:09
【问题描述】:

我有两个模型,一个是问题文本,第二个是针对用户和特定问题的答案。我一个用户已经回答了很多问题,给定一个问题,我怎样才能找到相应答案的索引?索引表示先前答案的数量/给定答案的位置。

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

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 排序)?

【问题讨论】:

    标签: django database model django-queryset


    【解决方案1】:

    我有!

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

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 2012-03-31
      • 2014-07-25
      • 2011-06-16
      • 2018-06-09
      相关资源
      最近更新 更多