如何在detailview(Django)中仅在ManytoManyfield上设置order_by



我有两个型号ClassStudentClassmdel中的一个字段与Student具有ManytoManyField关系。我想订购模板中有first_name的许多字段。我该怎么做?

型号.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

在模型元中设置ordering

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

您可以覆盖视图的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-相关

顺便说一句,通常ManyToManyField是复数,所以可以考虑将其更改为students

相关内容

  • 没有找到相关文章

最新更新