作为Django文档中轮询应用程序教程的扩展,我正在创建用户个人资料,我想获取特定用户对每个问题的回答并将其存储在数据库中,并能够列出对以下问题的所有回答用户在用户登录时回答所有问题。以及所有用户对问题的所有答复。本教程创建了两个模型:Question和Choice。(Choice的Question为ForeignKey)。但是,如何将特定用户选择的特定问题的选择附加到该同一用户?
这是我的模特。py
from django.db import models
import datetime
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Question(models.Model):
uzers = models.ManyToManyField(User)
question_text = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def published_recently(self):
return self.pub_date > timezone.now()
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Response(models.Model):
uzer = models.ForeignKey(User, on_delete = models.CASCADE)
question = models.ForeignKey(Question, on_delete= models.CASCADE)
response = models.ForeignKey(Choice, on_delete = models.CASCADE)
def __str__(self):
return self.uzer + self.question + self.response
datetime.timedelta(days=1)
views.py:
from .models import Choice, Question, Response
from django.contrib.auth.models import User
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
q = selected_choice.question
c = selected_choice
r= Response(uzer=User, question = q,response =c )
r.save()
#User.response_set(question = selected_choice.question, response = selected_choice )
selected_choice.save()
User.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
我也尝试过: User.response_set.create(问题= q,响应= c) 还尝试用“添加”替换“创建”。没用。