在Django ManyToManyField中订购用户

时间:2017-03-02 00:41:00

标签: python django sorting manytomanyfield

我有一个拥有ManyToManyField of Users的模型:

models.py

class Excuse(models.Model):
    students = models.ManyToManyField(User)
    reason = models.CharField(max_length=50)

views.py

def excuse_list(request, block_id=None):
    queryset = Excuse.objects.all().prefetch_related('students')
    context = {
        "object_list": queryset,
    }
    return render(request, "excuses/excuse_list.html", context)

模板(excuse_list.html)

...
{% for excuse in object_list %}
    <tr>
      <td>{{ excuse.reason }}</td>
      <td>
        {% for student in excuse.students.all %}
          {{student.get_full_name}};
        {% endfor %}
      </td>
    </tr>
{% endfor %}
...

如何按用户字段按字母顺序对用户集(excuse.students.all)进行排序,例如:user.last_name?

2 个答案:

答案 0 :(得分:1)

您只需更改views.py即可执行此操作:

queryset = Excuse.objects.all().prefetch_related(
Prefetch('students', queryset=User.objects.order_by('lastname')))
  

记得导入用户模型!

答案 1 :(得分:0)

您可以在Excuse模型中创建一个方法,该方法将返回已排序的学生集:

def get_sorted_students(self):
    return self.students.all().order_by('last_name')

然后在您的模板中使用excuse.get_sorted_students代替excuse.students.all

或者,您可以使用自定义模板标记来呈现学生列表。