我有两个型号Class
和Student
。Class
mdel中的一个字段与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
。