arianhf
arianhf

Reputation: 153

Sorting querysets by annotated field of reverse relation

I have 2 models, Form and Row, Each Row has a FK to a Form. I want to sort my Forms by the time of last row addition.

class Form(models.Model):
    ...

class Row(models.Model):
    form = models.ForeignKey(
        Form,
        related_name="rows",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
    )

I tried this but it doesnt work:

queryset = Form.objects.filter(is_empty=False)
queryset = queryset.annotate(last_submit=Max("rows__created_at")).order_by('-last_submit')

Upvotes: 1

Views: 619

Answers (1)

JPG
JPG

Reputation: 88499

After annotation, you need to call order_by() method.

sorted_qs = Form.objects.filter(is_empty=False
                                ).annotate(last_submit=Max("rows__created_at")
                                           ).order_by('-last_submit')

Update:

One possible cause not seeing the newly created Form instance at the beginning of the queryset is, some of the Row object may not have created_at value, so that becomes first. In such situations, you can change the order by behavior by setting nulls_last=True. For more details, ref this SO post, Django: Adding “NULLS LAST” to query

Upvotes: 2

Related Questions