简体   繁体   English

在 django 中使用不同的方法时如何使用过滤数据?

[英]How to use filtering data while using distinct method in django?

please help me on my problem I hope my title is enough to understand what I mean, please help me on this problem guys.请帮助我解决我的问题我希望我的标题足以理解我的意思,请帮助我解决这个问题。

When I tried this:当我尝试这个时:

id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct()

在此处输入图片说明 I use distinct() to eliminates duplicate rows of Students Enrollment Record from the query results but I wonder why the result is like this:我使用distinct()从查询结果中消除了学生注册记录的重复行,但我想知道为什么结果是这样的:

在此处输入图片说明

What should I do to show the Students name not that QuerySet in my html?我应该怎么做才能在我的 html 中显示学生姓名而不是 QuerySet?

This is my current views.py :这是我目前的views.py

id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct()
print(id_list)
grades = grade.objects.filter(Students_Enrollment_Records_id__in=id_list)
print(grades)

This is my models.py :这是我的models.py

class grade(models.Model):
    Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,
                                null=True, blank=True)
    Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE,
                                           null=True, blank=True)
    Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)
    Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+',
                                                    on_delete=models.CASCADE, null=True)
    Average = models.FloatField(null=True, blank=True)

UPDATE更新

when I tried this当我尝试这个时

piste = grade.objects.filter(Teacher_id=m.id).values_list('Students_Enrollment_Records').annotate(Average=Avg('Average')).order_by('Grading_Categories').distinct()

the computation is fix but the teacher name, Subject and Name of students didn't display but the ID is display just like this计算是固定的,但老师姓名,科目和学生姓名没有显示,但ID显示就像这样

在此处输入图片说明

this is my desire answer这是我想要的答案

在此处输入图片说明

this is how I post in html这就是我在 html 中发布的方式

views.py视图.py

return render(request, 'Homepage/index.html', {"piste":piste})

html html

{% for n in piste %}
          <tr>
              <td>{{n.Teacher}}</td>
              <td>{{n.Subjects}}</td>
              <td>{{n.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td>
              <td>{{n}}</td>
          </tr>
          {% endfor %}

This is model.py这是模型.py

class EmployeeUser(models.Model):
    Image = models.ImageField(upload_to='images', null=True, blank=True)
    Employee_Number = models.CharField(max_length=500, null=True)
    Username = models.CharField(max_length=500, null=True)
    Password = models.CharField(max_length=500, null=True)
    My_Department = models.ForeignKey(Department, related_name='+', on_delete=models.CASCADE, blank=True)
    My_Position = models.ForeignKey(Position, related_name='+', on_delete=models.CASCADE, blank=True)
    Firstname = models.CharField(max_length=500, null=True)
    Middle_Initial = models.CharField(max_length=500, null=True)
    Lastname = models.CharField(max_length=500, null=True)
    Educational_Attainment = models.ForeignKey(EducationalAttainment, related_name='+', on_delete=models.CASCADE,
                                               null=True)
    Landline = models.CharField(max_length=500, null=True)
    Mobile_Number = models.CharField(max_length=500, null=True)
    Email = models.CharField(max_length=500, null=True)
    Facebook_Acoount = models.CharField(max_length=500, null=True)

    Fathers_Firstname = models.CharField(max_length=500, null=True)
    Fathers_Middle_Initial = models.CharField(max_length=500, null=True)
    Fathers_Lastname = models.CharField(max_length=500, )
    Educational_Attainment_Father = models.ForeignKey(EducationalAttainment, related_name='+', on_delete=models.CASCADE,
                                                      null=True)
    Father_Occupation = models.CharField(max_length=500, null=True)
    Father_Company_Employed = models.CharField(max_length=500, null=True)
    Father_Landline = models.CharField(max_length=500, null=True)
    Father_MobileNo = models.CharField(max_length=500, null=True)
    Father_Email = models.CharField(max_length=500, null=True)
    Father_Facebook_Account = models.CharField(max_length=500, null=True)

    Mother_FirstName = models.CharField(max_length=500, null=True)
    Mother_Middle_Initial = models.CharField(max_length=500, null=True)
    Mother_Maiden_LastName = models.CharField(max_length=500, null=True)
    Educational_AttainmentID_Mother = models.ForeignKey(EducationalAttainment, related_name='+',
                                                        on_delete=models.CASCADE, null=True)
    Mother_Occupation = models.CharField(max_length=500, null=True)
    Mother_Company_Employed = models.CharField(max_length=500, null=True)
    Mother_Landline = models.CharField(max_length=500, null=True)
    Mother_MobileNo = models.CharField(max_length=500, null=True)
    Mother_Email = models.CharField(max_length=500, null=True)
    Mother_Facebook_Account = models.CharField(max_length=500, null=True)
    Family_Status = models.ForeignKey(FamilyStatu, related_name='+', on_delete=models.CASCADE, null=True)
    Country = models.CharField(max_length=500, null=True)
    ZIP_Postal_Code = models.CharField(max_length=500, null=True)
    State_Province = models.CharField(max_length=500, null=True)
    City = models.CharField(max_length=500, null=True)
    Barangay = models.CharField(max_length=500, null=True)
    Unit_Number_Street = models.CharField(max_length=500, null=True)
    LandMark = models.CharField(max_length=500, null=True)
    AddressLine1 = models.CharField(max_length=500, null=True)
    AddressLine2 = models.CharField(max_length=500, null=True)
    AddressLine3 = models.CharField(max_length=500, null=True)

    def __str__(self):
        suser = '{0.Firstname}   {0.Middle_Initial}      {0.Lastname}'
        return suser.format(self)

class StudentsEnrolledSubject(models.Model):
    Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+',
                                                    on_delete=models.CASCADE, null=True)
    Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,
                                                null=True)

this is the full view.py这是完整的view.py

m = EmployeeUser.objects.get(Username=request.POST['p_user'], Password = request.POST['p_pass'], My_Position =request.POST['position'])
piste = grade.objects.all().filter(Teacher=m.id).values_list('Students_Enrollment_Records').annotate(Average=Avg('Average')).order_by('Grading_Categories').distinct()
return render(request, 'Homepage/index.html', {"piste":piste})

UPDATE更新

when i tried this answer of mr @nigel222当我尝试@nigel222 先生的这个答案时

piste = grade.objects.filter(Teacher=m.id).annotate(grade_average=Avg('Average')).order_by('Grading_Categories').distinct()

and to my html和我的 html

{% for n in piste %}
      <tr>
          <td>{{n.Teacher}}</td> <!-- 1 -->
          <td>{{n.Subjects}}</td> <!-- 2 -->
          <td>{{n.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}
               </td>  <!-- 3 -->
          <td>{{n}}</td>  <!--4 -->
      </tr>
      {% endfor %}

i get this result我得到这个结果

在此处输入图片说明

I haven't worked with Django much for a couple of years, but this is what I think is happening.我已经有几年没有与 Django 一起工作了,但这就是我认为正在发生的事情。

You're assigning a values_list (a tuple) to piste .你分配values_list(元组)到piste You're not assigning grade objects to piste .您没有将grade对象分配给piste However, in your template you're expecting the elements of piste to be grades.但是,在您的模板中,您希望piste的元素是等级。

I believe you need to get the grade object first and send that to the template as well as the piste .我相信您需要先获取grade对象并将其发送到模板和piste

You don't want values_list (which is the data you are getting in column 4).您不想要values_list (这是您在第 4 列中获得的数据)。 You want a queryset of grade objects:你想要一个grade对象的查询集:

piste = grade.objects.filter(Teacher_id=m.id
        ).annotate(Average=Avg('Average')
        ).order_by('Grading_Categories'
        ).distinct()

and then in your template, something like然后在你的模板中,像

{% for n in piste %}
      <tr>
          <td>{{n.Teacher}}</td> <!-- 1 -->
          <td>{{n.Subjects}}</td> <!-- 2 -->
          <td>{{n.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}
               </td>  <!-- 3 -->
          <td>{{n}}</td>  <!--4 -->
      </tr>
      {% endfor %}

1 and 2 render EmployeeUser and Subject objects. 1 和 2 渲染EmployeeUserSubject对象。 1 will return the __str__ representation of EmployeeUser which ought to be OK. 1 将返回EmployeeUser__str__表示,这应该没问题。 Alternatively you can explicitly use {{n.Teacher.FirstName}} etc. in your template.或者,您可以在模板中明确使用{{n.Teacher.FirstName}}等。

3 I don't understand, because you don't show the Students_Enrolled_Subject model. 3 我不明白,因为你没有显示Students_Enrolled_Subject模型。

4 is now wrong. 4 现在错了。 Perhaps you want the annotation {{n.Average}} ?也许您想要注释{{n.Average}}

Please, as soon as possible, learn to use Django/ Python coding conventions.请尽快学习使用 Django/Python 编码约定。 Model subclasses (and Python class names in general) start with a capital letter. Model子类(以及一般的 Python 类名)以大写字母开头。 Instances of classes are lowercase.类的实例是小写的。 Fieldnames/attributes are normally lower_case and definitely start with a lowercase letter.字段名/属性通常是小写字母,并且肯定以小写字母开头。 Model subclass names are a singular name not a plural name.模型子类名称是单数名称而不是复数名称。 Not doing this is horribly confusing to any experiemced Django coder.不这样做对于任何有经验的 Django 编码员来说都是非常令人困惑的。 So,所以,

class Grade(models.Model):
    teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,
                            null=True, blank=True)
    grading_categories = models.ForeignKey(GradingCategory, related_name='+', on_delete=models.CASCADE,
                                       null=True, blank=True)
    subject = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)
    students_enrollment_records = models.ForeignKey(StudentsEnrolledSubject, related_name='+',
                                                on_delete=models.CASCADE, null=True)

This is the best I can do for you.这是我能为你做的最好的事情。 I think you should be selected based on the student and filtering the grades to the teacher.我认为您应该根据学生选择您并将成绩过滤给老师。 I also did a prefetch for all of the subjects since I can't quite tell what you need done there.我还对所有主题进行了预取,因为我不太清楚您需要在那里做什么。

students = Student.objects.filter(
    grades__teacher_id=teacher.id,
).annotate(
    total_avg=Avg('grades__Average')
).prefetch_related('grades__Subjects')

Template:模板:

{% for student in students %}
      <tr>
          <td>{{teacher}}</td>
          <td>{{student.grades.subjects.all}}</td>
          <td>{{student}}</td>
          <td>{{student.total_avg}}</td>
      </tr>
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM