所以我正在尝试查询我的数据库以查找具有user = request.user和id = 12的所有提交。我肯定知道有多个提交符合这个,但filter()只返回一个提交。我的查询出了什么问题?
由于
Submission.objects.filter(user=request.user, id=puzzleID)
编辑: 谢谢所有响应者。这是我提交和拼图的模型:
class Submission(models.Model):
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
)
puzzle = models.ForeignKey(
Puzzle,
on_delete=models.CASCADE,
)
userAnswer = models.TextField()
datetime = models.DateTimeField(default=datetime.now, blank=True)
class Puzzle(models.Model):
title = models.CharField(max_length=30)
question = models.TextField()
datetime = models.DateTimeField(
default=datetime.now,
blank=True)
# image = models.ImageField()
answer = models.TextField(default="answer")
trials = models.IntegerField(
default=1,
validators=[MinValueValidator(1)])
subject = models.CharField(
default="CS",
max_length=2,
choices=(
("CS", "Computer Science"),
)
)
编辑2: 这里也是查询的视图
puzzle = Puzzle.objects.get(id=puzzleID)
form = SubmitForm()
userTrials = len(Submission.objects.filter(user=request.user, puzzle=puzzle))
if userTrials >= puzzle.trials:
limitReached = True
else:
limitReached = False
return render(request, "puzzle.html", {
"puzzle": puzzle,
"form": form,
"userTrials": userTrials,
"remaining": puzzle.trials - userTrials,
"limitReached": limitReached,
})
答案 0 :(得分:3)
尝试查询拼图而不是ID,因为ID会引用提交ID,而不是拼图ID。
Submission.objects.filter(user = request.user, puzzle=puzzleID)