如何从具有两个外键的表中访问列?

时间:2019-05-10 16:35:48

标签: django view model

我正在尝试访问表中的列。该表有两个外键。

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

from django.db.models.signals import post_save



class Question(models.Model):
    question_id = models.IntegerField(default=0, unique=True)
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text


class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    answer_text = models.IntegerField()

    def __str__(self):
        return str(self.answer_text)


class UserProfile(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    image=models.ImageField(upload_to='',blank=True)
    points = models.IntegerField(default=0)

    def __str__(self):
        return self.user.username

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)



class Points_Tally(models.Model):
    userid=models.ForeignKey(User,on_delete=models.CASCADE)
    questions_id=models.ForeignKey(Question,on_delete=models.CASCADE)
    status=models.IntegerField(default=0)

    def __str__(self):
        return str(self.userid)

'''

这是我要访问状态表Points_Tally表的视图。

如果状态为零,则用户可以提交问题的答案,然后分数将增加,并且状态将被设置为1,因此,如果用户再次尝试回答问题,他将无法执行该操作。 / p>

'''

def detail(request, question_id,pk=None):
    question_data=get_object_or_404(Question,pk=question_id)
    if pk:
        user = User.objects.get(pk=pk)
    else:
        user = request.user


    form = forms.ValidateAnswerForm()
    points_tally_object = Points_Tally.objects.all()

    entire_data=[]
    for items in points_tally_object:
        entire_data.append(items.questions_id.question_id)
    #this is for the answer
    stored_ans = Answer.objects.all()
    answer_list = []
    for k in stored_ans:
        answer_list.append(k.answer_text)

    if request.method == 'POST':
        form = forms.ValidateAnswerForm(request.POST)
        if form.is_valid():
            print("validation successful")
            print(entire_data,"is the entire data")
            print(user,"This is the signed in user")
            print(user.userprofile.points)
            answer_given = form.cleaned_data['myanswers']
            print("answer",form.cleaned_data['myanswers'])
            print(answer_given)
            print(question_id,"is question_id")
            print("This is the user id",user.id)
            print("-------------Points tally and questions_id ")
            print(type(question_id),"Is the type of question_id")
            print(Points_Tally.status,"Is the type of question status")
            #user.userprofile.points+=10
            #user.userprofile.save()

            if Points_Tally.status==0:
                for i in answer_list:
                    if (answer_given==i):
                        print('Correct answer', i, '---', answer_given)
                        print("These are the points of the user before submitting answer", user.userprofile.points)
                        #question.userid=user.id
                        #question.questions_id=question_id
                        user.userprofile.points += 10
                        user.userprofile.save()
                        points_tally_object.status=1
                        points_tally_object.save()
                        print("This is my question status:",Points_Tally.status)
                        messages.success(request, "Your answer is correct")
                        break
                    else:
                        print("Wrong answer ")
                        print('answer mismatched', i, '---', answer_given)
                if (Points_Tally.status==0):
                  messages.error(request, "Please try again: Incorrect answer")
            else:
                print("You have already submitted answer to this:::",Points_Tally.status,"this is the status")
                messages.error(request, "You have already submitted answer to this question,Please try another question")

        else:
            print("I am in else of form is invalid")
            #return redirect('account:detail', pk=question_id)
    else:
        print("I am in else")
    return render(request, 'account/detail.html', {'form': form, 'question': points_tally_object,'question_data':question_data})

'''

1 个答案:

答案 0 :(得分:0)

您必须选择一个特殊对象,然后获取所需的列。您刚刚提到了Models名称,并试图获取该列。那是错的。 这与外键无关。