我想检查练习页面的ID是否在一个SolvedExercises数组的内部。我认为使用contained_by可能很容易,但是它不起作用。
我已经尝试过这一行(但我也想将问题随机化)
randomQuestions = Exercises.objects.filter(id__contained_by=(req.user.profile.exercitiiProvocari).order_by("?")
但是它不起作用。 我收到此错误:
Unsupported lookup 'contained_by' for AutoField or join on the field not permitted, perhaps you meant contains or icontains?
我想这个错误是由于ID是django自动生成的字段,但我不知道如何解决它。
views.py
from django.shortcuts import render
from exercitii.models import Exercises
# Create your views here.
def index(req):
return render(req, "../templates/pagini/provocari.html")
def provocari(req):
randomQuestions = Exercises.objects.filter(id__contained_by=(req.user.profile.exercitiiProvocari).order_by("?")
print(randomQuestions)
return render(req, "../templates/pagini/provocare.html")
锻炼模型
from django.db import models
from django.contrib.postgres.fields import ArrayField
from lectii.models import Lectie
# Create your models here.
class Exercises(models.Model):
idLectie = models.ForeignKey(Lectie, on_delete=models.DO_NOTHING, blank=True, null=True)
intrebare = models.CharField(max_length = 300)
variante = ArrayField(models.CharField(max_length=300), null=True)
variantaCorecta = models.CharField(max_length = 1)
def __str__(self):
return self.intrebare
所以我实际上是在尝试使所有练习的数组与已解决的练习的ID有所不同,并将结果随机化。
但是当我试图做到这一点时,我得到了那个错误。
答案 0 :(得分:1)
在这种情况下,简单的in
lookup就足够了吗?
假设req.user.profile.exercitiiProvocari
是某种数组/列表/容器,则可以尝试如下操作:
randomQuestions = Exercises.objects.filter(id__in=req.user.profile.exercitiiProvocari)\
.order_by("?")
要排除似乎存在的问题,您可以尝试使用exclude()
。这将返回所有不在req.user.profile.exercitiiProvocari
中的问题,它们应该是随机的:
randomQuestions = Exercises.objects.exclude(id__in=req.user.profile.exercitiiProvocari)\
.order_by("?")