如何在单个视图中从多个模型进行查询

时间:2019-06-01 09:41:38

标签: django python-3.x

我正在学校安置系统上工作,我有多个模型可供查询。首先,我想遍历学生列表,并检查个人资料和结果模型中两个学生的ID是否匹配。然后,我将检查学生是否已通过,然后安置该学生。

我正在使用Django 2.2.1。我做了很多搜索,但无济于事。以下是我的一些代码。

这是我的学生模特。

    <div class="wrapper" style="width: 400px; height: 400px; display: flex; position: relative;">
      <canvas></canvas>
      <svg style="position: absolute" width="100%" height="100%">
        <g transform="translate(200, 200)">
          <circle cx="0" cy="0" r="30" fill="red"/>
          <text x="-12" y="2" font-family="Arial" font-size="15px" fill="black">SVG</text>
        </g>
      </svg>
    </div>

    <script>
      const canvas = document.querySelector('canvas');
      const ctx = canvas.getContext('2d');

      canvas.width = 400;
      canvas.height = 400;

      ctx.fillStyle = "pink"
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = 'black';
      ctx.font = '20px Arial';
      ctx.fillText("Canvas", canvas.width / 2, 50);
    </script>

这是我的结果上传模型

class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Extra Fields
    student_ID = models.CharField(max_length=10)
    middle_Name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES)
    disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES)
    locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES)
    age = models.PositiveIntegerField()
    profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg')

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

这是我的学校选择模型。我有五个,除了名字改变外,其他都一样。

class StudentResultsUpload(models.Model):
    # student = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    student_ID = models.CharField(max_length=10)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)

这是我的views.py。

class SchoolSelectionOne(models.Model):
    student = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    name_of_School = models.CharField(max_length=100)
    program = models.CharField(max_length=50)
    residential_Status = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

但是当我运行它时,这是我得到的错误:

def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    school_one = SchoolSelectionOne.objects.all()
    school_two = SchoolSelectionTwo.objects.all()
    school_three = SchoolSelectionThree.objects.all()
    school_four = SchoolSelectionFour.objects.all()
    school_five = SchoolSelectionFive.objects.all()

    for candidate in profile:
        if profile.student_ID == place.student_ID:
            if (place.english >= 50 and place.mathematics >= 50 and place.integrated_Science >= 50 and place.social_Studies >= 50):
                raw_score = (place.english + place.mathematics + place.integrated_Science + place.social_Studies + place.basic_Design_Technology + place.home_Economics)

                for school in zip(school_one, school_two, school_three, school_four, school_five):
                    if raw_score >= 480:
                        place_me = school_one
                    elif raw_score >= 420:
                        place_me = school_two
                    elif raw_score >= 360:
                        place_me = school_three
                    elif raw_score >= 300:
                        place_me = school_four
                    else:
                        place_me = school_five

                    return render(request, 'schools/placement.html', {'place_me': place_me})
            else:
                return HttpResponse("You did not qualify for placement.")

我希望能够安置所有有资格获得安置的学生。

3 个答案:

答案 0 :(得分:1)

Daniel Roseman所示,您应该使用外键来关联不同的模型。重构代码应类似于以下代码。

StudentResultsUpload模型

let arr = person.map(x => {
  return `My name is ${x.name}, I am ${x.nationality} and I am ${x.age}`;
})

SchoolSelectionOne模型

arr.join(', ');

展示位置功能

class StudentResultsUpload(models.Model):
    student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, null=True)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)

在避免使用嵌套的放置功能中,我首先找到了每个候选人的所需信息(假设每个候选人都与学校关联并上传了模型),然后进行了计算。

答案 1 :(得分:0)

在这两行上

for candidate in profile:
    if profile.student_ID == place.student_ID:

您表示要在循环内使用candidate作为变量名,因此第二行可能应读为if candidate.student_ID而不是if profile.student_ID

答案 2 :(得分:0)

place是一个查询集。因此必须对其进行迭代。

尝试此代码:

def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    school_one = SchoolSelectionOne.objects.all()
    school_two = SchoolSelectionTwo.objects.all()
    school_three = SchoolSelectionThree.objects.all()
    school_four = SchoolSelectionFour.objects.all()
    school_five = SchoolSelectionFive.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:
            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):
                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)

                    if raw_score >= 480:
                        place_me = school_one
                    elif raw_score >= 420:
                        place_me = school_two
                    elif raw_score >= 360:
                        place_me = school_three
                    elif raw_score >= 300:
                        place_me = school_four
                    else:
                        place_me = school_five

                    placements.append({'student': candidate, 'school': place_me})
    return render(request, 'schools/placement.html', {'place_me': placements})

placement.html:

<div class="container">
    <p id="success">
        Placement Here.
    </p>
    {% for placement in place_me %}
        Stdudent Id: {{ placement.student.student_ID }}
        Stdudent middle name: {{ placement.student.middle_Name }}
        Stdudent gender: {{ placement.student.gender }}

        Placements:
            {% for school in placement.school %}
                {{ school }}
            {% endfor %}
    {% endfor %}
</div>