如何仅在详细视图(Django)中的 ManytoManyfield 上设置 order_by?

How to set order_by only on ManytoManyfield in detailview (Django)?

我有 2 个模型 ClassStudentClass mdel 中的一个字段与 StudentManytoManyField 关系。我想在模板中使用 first_name 订购 manytomanyfield。我该怎么做?

models.py

class Student(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True)
    first_name = models.CharField(max_length=100)


class Class(models.Model):
    student = models.ManyToManyField(Student)
    subject = models.CharField(max_length=150, unique=True)
    # many other fields

views.py

class Class_detailView(LoginRequiredMixin, DetailView):
    login_url = '/'
    model = Class
    template_name = "attendance/content/teacher/class_detail.html

模板

<div class="row ml-auto mr-auto">
  <h6>{{ object.subject }}</h6>
  {% for student in object.student.all %}
    <h6 id="class-detail-text" class="mt-2">
      {{student.first_name}} <-- want to order here
    </h6>
  {% endfor %}
</div>

现在名称呈现如下:

Freaky  Albon  Bucky

我希望它这样排序:

Albon   Bucky  Freaky

在模型 meta

中设置 ordering
class Student(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True)
    first_name = models.CharField(max_length=100)

    <b>class Meta:
        ordering = ('first_name',)</b>

您可以只覆盖视图的 queryset 属性。如果您总是希望在您访问它的任何时候进行排序,您也可以使用 Student 模型的 Meta 属性。

from django.db.models import Prefetch

class Class_detailView(LoginRequiredMixin, DetailView):
    queryset = Class.objects.prefetch_related(Prefetch('student', queryset=Student.objects.order_by('name'))
    login_url = '/'
    model = Class
    template_name = "attendance/content/teacher/class_detail.html

请参阅 prefetch_related 上的文档: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#prefetch-related

顺便说一句,通常 ManyToManyField 是复数形式,因此请考虑将其更改为 students