1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

I will add that now, i forget to mention it. I am using this, but it doesn't seem to be working. the order changes, but when I add a new row, it doesnt come to the front of the query.
" I add a new row, it doesnt come to the front of the query..." Which instance did you add? Form or Row?
well for example if I add a row with created_at=now(), I want the corresponding form to be the first form after ordering, but this does not happen.
so i found out my code was working fine, except there are some forms that have no submits, and django thinks that None is greater than any date :))
in such case, use this ordering technique, Django: Adding “NULLS LAST” to query
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.