简体   繁体   English

Django:如何通过related_field中的特定条目来order_by?

[英]Django: how to order_by a specific entry in a related_field?

I have a typical ForeignKey relationship in Django: 我在Django中有一个典型的ForeignKey关系:

class SchoolYear(models.Model):
    pass

class CycleHeader(models.Model):
    schoolyear = models.ForeignKey(SchoolYear, related_name="cycles")
    # Index is D, or A1-A4
    index = models.CharField(max_length=2)
    value = models.IntegerField()

Every SchoolYear may have up to 5 CycleHeaders. 每个学年最多可以有5个CycleHeader。 If there is any CycleHeader at all, there is a D record. 如果根本没有任何CycleHeader,则存在D记录。 Sometimes there are also records for A1-A4. 有时也有A1-A4的记录。 I need to sort the SchoolYear records by the value field of the D record. 我需要按D记录的value字段对SchoolYear记录进行排序。

If I use schoolyears.order_by('cycles_ index', 'cycles _value'), the results vary by how many CycleHeader records there are. 如果我使用schoolyears.order_by('cycles_ index','cycles _value'),则结果因存在多少CycleHeader记录而异。 What I'd like to do is annotate the schoolyear records with either the D record or the value of the D record, and I can't seem to figure out a way to do that. 我想做的是用D记录或D记录的值注释学年记录,但我似乎想不出办法。 Am I missing something? 我想念什么吗?

Here's the solution I eventually came up with thanks to the hints: 由于提示,我最终想出了以下解决方案:

    # schoolyears is a QuerySet based on earlier filtering

    schoolyears1 = schoolyears.filter(cycles__index='D').order_by('cycles__value', 'school__name')
    schoolyears2 = schoolyears.filter(cycles__isnull=True).order_by('school__name')
    schoolyears = schoolyears2 | schoolyears1

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

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