【发布时间】:2022-12-10 10:45:34
【问题描述】:
我在 python 3.10.8 中使用 django 4.1.2。我有三种模型,一种用于用户管理,一种用于问题,另一种用于答案。它们描述如下:
class User(AbstractUser):
phone_number = models.CharField(max_length=14, unique=True)
first_name = models.CharField(max_length=40)
father_name = models.CharField(max_length=40)
email = models.EmailField(unique=True, required=True)
age = models.CharField(max_length=3)
username = models.CharField(max_length=8, required=True)
class Question(models.Model):
question = models.CharField(
max_length=500,
null=False,
unique=True
)
creating_staff = models.ForeignKey(
User,
null=False,
on_delete=models.PROTECT,
to_field="phone_number",
)
options = models.JSONField(null=False)
correct_option = models.CharField(max_length=250, null=False)
question_ts = models.DateTimeField(auto_now_add=True, null=False)
class Meta:
verbose_name = "Question"
def __str__(self) -> str:
return f"{self.question}"
class Answer(models.Model):
answer = models.CharField(max_length=500, null=False)
question_answered = models.ForeignKey(
Question,
null=False,
on_delete=models.PROTECT,
related_name="question_answered"
)
answering_user = models.ForeignKey(
User,
null=False,
on_delete=models.PROTECT,
to_field="phone_number",
related_name="answerer"
)
status = models.BooleanField(null=False)
answer_ts = models.DateTimeField(auto_now_add=True, null=False)
class Meta:
verbose_name = "Answer"
def __str__(self) -> str:
return f"{self.answer} -- {self.answering_user}"
这是urls.py 文件:
from django.urls import path
from .views import (AnswerView)
app_name = "commons"
urlpatterns = [
path("play/", AnswerView.as_view(), name="play"),
]
我正在尝试做的是,每当用户登录并想通过转到 /commons/play/ 来回答一组问题时,在 GET 请求上,我想解析出用户之前回答过的所有问题,并且总是通过从未回答的问题中随机选择 10 个来显示新问题。
到目前为止我所做的是:
import random
from django.shortcuts import (redirect, render)
from django.views import View
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import (Question, Answer, User)
class AnswerView(LoginRequiredMixin, View):
def get(self, request):
answerer = request.user
total_answers_by_user = Answer.objects.filter(answering_user=answerer)
questions = Question.objects.all()
question_list = list()
for ans in total_answers_by_user:
for q in questions:
if not ans.question_answered == q:
question_list.append(q)
questions_count = question.count()
try:
rand_sample = random.sample(range(questions_count), 10)
except (ValueError, Exception) as e:
print(f"{e} population for random sample < 10, perhaps new player")
total_questions = Question.objects.all().count()
rand_sample = random.sample(range(total_questions), 10)
questions_to_ask = Question.objects.filter(id__in=rand_sample)
else:
questions_to_ask = Question.objects.filter(id__in=rand_sample)
return render(request, "commons/answer.html", {"questions": questions_to_ask})
但我非常怀疑这是一种检索未回答问题或新问题的有效方法,尤其是当涉及到多个用户时。有没有更好的方法来检索用户之前回答过的所有问题,并且只显示新的或未回答的问题?
感谢您的回复。
【问题讨论】:
标签: python-3.x django django-models django-views django-4.1