简体   繁体   English

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

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

I have 2 models Class and Student .我有 2 个模型ClassStudent One field within the Class mdel has a ManytoManyField relationship with Student . Class mdel 中的一个ManytoManyFieldStudent具有ManytoManyField关系。 I want to order the manytomanyfield with first_name in the template.我想在模板中使用first_name订购 manytomanyfield。 How can I do it?我该怎么做?

models.py模型.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视图.py

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

template模板

<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>

right now the names render like this:现在名称呈现如下:

Freaky  Albon  Bucky

I want it to order like this:我希望它这样订购:

Albon   Bucky  Freaky

Set ordering in the model meta在模型元中设置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',)

You can just override the queryset attribute of your view.您可以只覆盖视图的queryset属性。 You can also use the Meta attribute of the Student model if you always want the ordering to take place any time you access it.如果您始终希望在访问它时进行排序,您还可以使用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

See docs on prefetch_related : https://docs.djangoproject.com/en/3.1/ref/models/querysets/#prefetch-related请参阅有关prefetch_related文档: https : //docs.djangoproject.com/en/3.1/ref/models/querysets/#prefetch-related

As an aside, usually ManyToManyField 's are pluralized, so consider changing it to students .顺便说一句,通常ManyToManyField的是多元状态,因此考虑将其更改为students

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

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