我想检查练习页面的 id 是否位于已解决练习的数组内。我认为使用 contains_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 自动生成的字段,但我不知道如何修复它。
View .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 的数组进行区分,并将结果随机化。
但是当我试图做出这种改变时,我收到了这个错误。
最佳答案
这不是简单的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("?")
关于python - 以默认 ID 作为参数包含的不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55635210/