[Answered ]-Order Django Queryset by attribute that could be char or int?

1πŸ‘

βœ…

It’s not pretty, but as far as i have understood your question it does the job

grades_list = (
    all_enrollments.values_list("first_letter_group", flat=True)
    .order_by("first_letter_group")
    .distinct()
    .values_list("first_letter_group", flat=True)
)  # List of only the integer grades
int_grades_list = list(
    map(
        lambda x: int(x),
        filter(lambda x: x.isdigit(), grades_list),
    )
)  # Gives a dynamic list of only ints: [1, 2, 3, 4, 5, 6, 8, 10, etc..]


ordered_enrollment_list = (
        all_enrollments.annotate(
            number_field=Case(
                  When(first_letter_group__in=int_grades_list, then=Cast(F('first_letter_group'), IntegerField())),
                  default=Value(0),
                  output_field=IntegerField()
               ),
            str_field=Case(
                  When(first_letter_group__in=int_grades_list, then=Value(False)),
                  default=Cast(F('first_letter_group'), CharField()),
                  output_field=CharField()
               ),
        )
        .order_by('-str_field', 'number_field')
    )
πŸ‘€PTomasz

Leave a comment