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

Posted

技术标签:

【中文标题】如何从具有两个外键的表中访问列?【英文标题】:How to access a column from a table having two foreign keys? 【发布时间】:2019-09-28 14:24:45 【问题描述】:

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

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,这样如果用户再次尝试回答,他将无法这样做。

'''

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)

'''

【问题讨论】:

我无法使用 get 检索单个对象。 【参考方案1】:

你必须选择一个特殊的对象,然后得到想要的列。您刚刚提到了模型名称并试图获取该列;那是错的。 这与外键无关。

【讨论】:

我怎样才能选择一个特殊的对象,然后得到想要的列?我刚刚开始学习 Django,现在在过去三天里解决了这个问题,但我无法这样做。请帮帮我。 您必须在 Points_Tally 模型中为您的外键定义一个 related_name,然后在您的视图中循环一个特殊的 answer_given 后,获取与以下答案模型对象相关的所有 Points_Tally通过定义的related_name。 我还是没有得到任何东西,请帮我写代码。

以上是关于如何从具有两个外键的表中访问列?的主要内容,如果未能解决你的问题,请参考以下文章

如何从特定数据库中的所有表中检索不属于主键和外键的所有列

如何在 SAP ASE Sybase 16 中从具有外键的表中删除行

从具有三个外键的表中选择一个表[关闭]

使用外键约束

我有两个带外键的表,我想在第一个表中按下外键,第二个表出现数据

实体框架代码优先:具有两个外键的表