﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
31691	Added ordering support to JSONBAgg.	john-parton	john-parton	"Here's a contrived example:

{{{#!python
class Author(models.Model):
    name = models.CharField(max_length=50)
    alias = models.CharField(max_length=50, null=True, blank=True)
    age = models.PositiveSmallIntegerField(default=30)


class Article(models.Model):
    authors = models.ManyToManyField(Author, related_name='articles')
    title = models.CharField(max_length=50)
    
    
Article.objects.annotate(
    authors_json=JSONBAgg(
        Func(
            Value('name'), 'name',
            Value('alias'), 'alias',
            function='jsonb_build_object'
        ),
        ordering='age'
    )
)
}}}

The ordering kwarg is ignored, but Postgres would have no problem understanding the aggregate with an ORDER BY clause

In my code I did the following

{{{#!python
class OrderableJSONBAgg(OrderableAggMixin, Aggregate):
    function = 'JSONB_AGG'
    template = '%(function)s(%(expressions)s %(ordering)s)'
    output_field = JSONField()

    def convert_value(self, value, expression, connection):
        if not value:
            return []
        return value
    
    
from myapp.aggregates import OrderableJSONBAgg as JSONBAgg
}}}

I believe replacing the existing JSONBAgg with this implementation would add the feature, with no backwards compat issues.

I would be happy to submit a pull request."	New feature	closed	contrib.postgres	dev	Normal	fixed			Accepted	1	0	0	0	0	0
